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
;
232 struct layer
*flayer
;
235 struct win
*console_window
;
244 char strnomem
[] = "Out of memory.";
247 static int InterruptPlease
;
248 static int GotSigChld
;
251 lf_secreopen(name
, wantfd
, l
)
259 if (((got_fd
= secopen(name
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666)) < 0) ||
260 lf_move_fd(got_fd
, wantfd
) < 0)
263 debug1("lf_secreopen: failed for %s\n", name
);
266 l
->st
->st_ino
= l
->st
->st_dev
= 0;
267 debug2("lf_secreopen: %d = %s\n", wantfd
, name
);
271 /********************************************************************/
272 /********************************************************************/
273 /********************************************************************/
276 static struct passwd
*
277 getpwbyname(name
, ppp
)
283 struct spwd
*sss
= NULL
;
284 static char *spw
= NULL
;
287 if (!ppp
&& !(ppp
= getpwnam(name
)))
290 /* Do password sanity check..., allow ##user for SUN_C2 security */
295 if (ppp
->pw_passwd
[0] == '#' && ppp
->pw_passwd
[1] == '#' &&
296 strcmp(ppp
->pw_passwd
+ 2, ppp
->pw_name
) == 0)
300 char c
= ppp
->pw_passwd
[n
];
301 if (!(c
== '.' || c
== '/' || c
== '$' ||
302 (c
>= '0' && c
<= '9') ||
303 (c
>= 'a' && c
<= 'z') ||
304 (c
>= 'A' && c
<= 'Z')))
309 /* try to determine real password */
310 if (n
< 13 && sss
== 0)
312 sss
= getspnam(ppp
->pw_name
);
317 ppp
->pw_passwd
= spw
= SaveStr(sss
->sp_pwdp
);
318 endspent(); /* this should delete all buffers ... */
321 endspent(); /* this should delete all buffers ... */
327 if (ppp
->pw_passwd
&& strlen(ppp
->pw_passwd
) == 13 + 11)
328 ppp
->pw_passwd
[13] = 0; /* beware of linux's long passwords */
343 char socknamebuf
[2 * MAXSTR
];
345 char *myname
= (ac
== 0) ? "screen" : av
[0];
348 #ifdef _MODE_T /* (jw) */
353 #if defined(SYSV) && !defined(ISC)
354 struct utsname utsnam
;
356 struct NewWindow nwin
;
357 int detached
= 0; /* start up detached */
362 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
363 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
365 #if defined(sun) && defined(SVR4)
367 /* Solaris' login blocks SIGHUP! This is _very bad_ */
370 sigprocmask(SIG_SETMASK
, &sset
, 0);
375 * First, close all unused descriptors
376 * (otherwise, we might have problems with the select() call)
382 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
383 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
384 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
385 debug2("-- screen debug started %s (%s)\n", *av
, version
);
399 debug("NAMEDPIPE\n");
401 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
402 debug("Window size changing enabled\n");
432 debug1("NAME_MAX = %d\n", NAME_MAX
);
435 BellString
= SaveStr("Bell in window %n");
436 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
437 ActivityString
= SaveStr("Activity in window %n");
438 screenlogfile
= SaveStr("screenlog.%n");
439 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
440 hstatusstring
= SaveStr("%h");
441 captionstring
= SaveStr("%3n %t");
442 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
443 wlisttit
= SaveStr("Num Name%=Flags");
444 wliststr
= SaveStr("%3n %t%=%f");
446 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
452 default_startup
= (ac
> 1) ? 0 : 1;
454 VBellWait
= VBELLWAIT
* 1000;
455 MsgWait
= MSGWAIT
* 1000;
456 MsgMinWait
= MSGMINWAIT
* 1000;
457 SilenceWait
= SILENCEWAIT
;
462 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
463 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
467 CompileKeys((char *)0, 0, mark_key_tab
);
471 screenencodings
= SaveStr(SCREENENCODINGS
);
474 nwin_options
= nwin_undef
;
475 strcpy(screenterm
, "screen");
477 logreopen_register(lf_secreopen
);
480 /* if this is a login screen, assume -RR */
489 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
494 if (--ac
> 0 && *ap
== '-')
496 if (ap
[1] == '-' && ap
[2] == 0)
502 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
503 Panic(0, "Screen version %s", version
);
504 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
505 exit_with_usage(myname
, NULL
, NULL
);
506 while (ap
&& *ap
&& *++ap
)
511 nwin_options
.aflag
= 1;
516 case 'p': /* preselect */
522 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
529 bd
.bd_start_braille
= 1;
538 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
547 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
551 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
560 nwin_options
.flowflag
= FLOW_NOW
* 0;
567 nwin_options
.flowflag
= FLOW_NOW
* 1;
570 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
573 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
578 exit_with_usage(myname
, NULL
, NULL
);
579 nwin_options
.histheight
= atoi(*++av
);
580 if (nwin_options
.histheight
< 0)
581 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
586 case 't': /* title, the former AkA == -k */
588 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
589 nwin_options
.aka
= *++av
;
597 nwin_options
.lflag
= 0;
604 nwin_options
.lflag
= 1;
607 nwin_options
.lflag
= 3;
610 case 'i': /* -list */
612 if (ac
> 1 && !SockMatch
)
620 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
626 if (ac
> 1 && !SockMatch
)
633 nwin_options
.Lflag
= 1;
638 case 'O': /* to be (or not to be?) deleted. jw. */
643 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
644 if (strlen(*++av
) < 20)
645 strcpy(screenterm
, *av
);
647 Panic(0, "-T: terminal name too long. (max. 20 char)");
648 nwin_options
.term
= screenterm
;
658 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
662 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
670 rflag
+= (*ap
== 'R') ? 2 : 1;
681 if (*av
[1] != '-' && !SockMatch
)
685 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
692 exit_with_usage(myname
, "Specify shell with -s", NULL
);
695 ShellProg
= SaveStr(*++av
);
696 debug1("ShellProg: '%s'\n", ShellProg
);
702 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
706 exit_with_usage(myname
, "Empty session-name?", NULL
);
712 Panic(0, "Screen version %s", version
);
716 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
720 exit_with_usage(myname
, "Unknown option %s", --ap
);
732 if (eff_uid
!= real_uid
)
734 /* if running with s-bit, we must install a special signal
735 * handler routine that resets the s-bit, so that we get a
738 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
739 signal(SIGBUS
, CoreDump
);
741 signal(SIGSEGV
, CoreDump
);
745 setlocale(LC_ALL
, "");
748 if (nwin_options
.encoding
== -1)
750 /* ask locale if we should start in UTF-8 mode */
751 # ifdef HAVE_NL_LANGINFO
753 setlocale(LC_CTYPE
, "");
755 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
756 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
760 if (((s
= getenv("LC_ALL")) || (s
= getenv("LC_CTYPE")) ||
761 (s
= getenv("LANG"))) && InStr(s
, "UTF-8"))
762 nwin_options
.encoding
= UTF8
;
764 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
768 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
769 Panic(0, "Ridiculously long socketname - try again.");
770 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
772 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
776 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
781 /* make the write() calls return -1 on all errors */
784 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
785 * It appears that in System V Release 4, UNIX, if you are writing
786 * an output file and you exceed the currently set file size limit,
787 * you _don't_ just get the call to `write' returning with a
788 * failure code. Rather, you get a signal called `SIGXFSZ' which,
789 * if neither handled nor ignored, will cause your program to crash
792 signal(SIGXFSZ
, SIG_IGN
);
796 signal(SIGPIPE
, SIG_IGN
);
803 sh
= getenv("SHELL");
804 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
806 ShellArgs
[0] = ShellProg
;
807 home
= getenv("HOME");
810 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
812 char nethackrc
[MAXPATHLEN
];
814 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
816 sprintf(nethackrc
,"%s/.nethackrc", home
);
817 nethackflag
= !access(nethackrc
, F_OK
);
823 own_uid
= multi_uid
= real_uid
;
824 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
827 Panic(0, "Must run suid root for multiuser support.");
830 SockMatch
= sockp
+ 1;
834 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
835 Panic(0, "Cannot identify account '%s'.", multi
);
836 multi_uid
= mppp
->pw_uid
;
837 multi_home
= SaveStr(mppp
->pw_dir
);
838 if (strlen(multi_home
) > MAXPATHLEN
- 10)
839 Panic(0, "home directory path too long");
841 /* always fake multi attach mode */
849 if (SockMatch
&& *SockMatch
== 0)
851 #endif /* MULTIUSER */
853 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
855 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
856 if ((int)ppp
->pw_uid
!= real_uid
)
857 ppp
= (struct passwd
*) 0;
861 if ((ppp
= getpwuid(real_uid
)) == 0)
863 Panic(0, "getpwuid() can't identify your account!");
866 LoginName
= ppp
->pw_name
;
868 LoginName
= SaveStr(LoginName
);
870 ppp
= getpwbyname(LoginName
, ppp
);
872 #if !defined(SOCKDIR) && defined(MULTIUSER)
873 if (multi
&& !multiattach
)
875 if (home
&& strcmp(home
, ppp
->pw_dir
))
876 Panic(0, "$HOME must match passwd entry for multiuser screens.");
880 if (home
== 0 || *home
== '\0')
882 if (strlen(LoginName
) > 20)
883 Panic(0, "LoginName too long - sorry.");
885 if (multi
&& strlen(multi
) > 20)
886 Panic(0, "Screen owner name too long - sorry.");
888 if (strlen(home
) > MAXPATHLEN
- 25)
889 Panic(0, "$HOME too long - sorry.");
892 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
))
898 /* ttyname implies isatty */
899 if (!(attach_tty
= ttyname(0)))
900 Panic(0, "Must be connected to a terminal.");
901 if (strlen(attach_tty
) >= MAXPATHLEN
)
902 Panic(0, "TtyName too long - sorry.");
903 if (stat(attach_tty
, &st
))
904 Panic(errno
, "Cannot access '%s'", attach_tty
);
906 tty_mode
= (int)st
.st_mode
& 0777;
910 fl
= fcntl(0, F_GETFL
, 0);
911 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
916 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
917 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
920 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
922 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
923 Panic(0, "Please set a terminal type.");
924 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
925 Panic(0, "$TERM too long - sorry.");
926 GetTTY(0, &attach_Mode
);
927 #ifdef DEBUGGGGGGGGGGGGGGG
928 DebugTTY(&attach_Mode
);
933 oumask
= umask(0); /* well, unsigned never fails? jw. */
935 if ((oumask
= (int)umask(0)) == -1)
936 Panic(errno
, "Cannot change umask to zero");
938 SockDir
= getenv("SCREENDIR");
941 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
942 Panic(0, "Ridiculously long $SCREENDIR - try again.");
945 Panic(0, "No $SCREENDIR with multi screens, please.");
952 sprintf(SockPath
, "%s/.screen", multi_home
);
956 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
965 sprintf(SockPath
, "%s/.screen", home
);
971 if (access(SockDir
, F_OK
))
973 debug1("SockDir '%s' missing ...\n", SockDir
);
974 if (UserContext() > 0)
976 if (mkdir(SockDir
, 0700))
980 if (UserStatus() <= 0)
981 Panic(0, "Cannot make directory '%s'.", SockDir
);
983 if (SockDir
!= SockPath
)
984 strcpy(SockPath
, SockDir
);
990 if (lstat(SockDir
, &st
))
992 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
993 (eff_gid
!= real_gid
) ? 0775 :
999 if (mkdir(SockDir
, n
) == -1)
1000 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1004 if (!S_ISDIR(st
.st_mode
))
1005 Panic(0, "'%s' must be a directory.", SockDir
);
1006 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1007 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1008 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1009 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1011 if (((int)st
.st_mode
& 0777) != n
)
1012 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1014 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1015 if (access(SockPath
, F_OK
))
1017 if (mkdir(SockPath
, 0700) == -1)
1018 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1019 (void) chown(SockPath
, real_uid
, real_gid
);
1025 if (stat(SockPath
, &st
) == -1)
1026 Panic(errno
, "Cannot access %s", SockPath
);
1028 if (!S_ISDIR(st
.st_mode
))
1029 Panic(0, "%s is not a directory.", SockPath
);
1033 if ((int)st
.st_uid
!= multi_uid
)
1034 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1039 if ((int)st
.st_uid
!= real_uid
)
1040 Panic(0, "You are not the owner of %s.", SockPath
);
1042 if ((st
.st_mode
& 0777) != 0700)
1043 Panic(0, "Directory %s must have mode 700.", SockPath
);
1044 if (SockMatch
&& index(SockMatch
, '/'))
1045 Panic(0, "Bad session name '%s'", SockMatch
);
1046 SockName
= SockPath
+ strlen(SockPath
) + 1;
1048 (void) umask(oumask
);
1049 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1051 #if defined(SYSV) && !defined(ISC)
1052 if (uname(&utsnam
) == -1)
1053 Panic(errno
, "uname");
1054 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1055 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1057 (void) gethostname(HostName
, MAXSTR
);
1058 HostName
[MAXSTR
- 1] = '\0';
1060 if ((ap
= index(HostName
, '.')) != NULL
)
1069 real_uid
= multi_uid
;
1075 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1077 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1079 Panic(0, "No Sockets found in %s.\n", SockPath
);
1080 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1083 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1088 /* attach_tty is not mandatory */
1089 if ((attach_tty
= ttyname(0)) == 0)
1091 if (strlen(attach_tty
) >= MAXPATHLEN
)
1092 Panic(0, "TtyName too long - sorry.");
1094 Panic(0, "Please specify a command.");
1099 if (!mflag
&& !SockMatch
)
1101 sty
= getenv("STY");
1102 if (sty
&& *sty
== 0)
1105 SendCmdMessage(sty
, SockMatch
, av
);
1108 else if (rflag
|| xflag
)
1110 debug("screen -r: - is there anybody out there?\n");
1111 if (Attach(MSG_ATTACH
))
1118 Panic(0, "Can't create sessions of other users.");
1120 debug("screen -r: backend not responding -- still crying\n");
1122 else if (dflag
&& !mflag
)
1124 (void) Attach(MSG_DETACH
);
1125 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1129 if (!SockMatch
&& !mflag
)
1133 if ((sty
= getenv("STY")) != 0 && *sty
!= '\0')
1139 nwin_options
.args
= av
;
1140 SendCreateMsg(sty
, &nwin
);
1145 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1147 if (!detached
|| dflag
!= 2)
1155 Panic(errno
, "fork");
1163 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1165 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1166 for (ap
= socknamebuf
; *ap
; ap
++)
1170 if (strlen(socknamebuf
) > NAME_MAX
)
1171 socknamebuf
[NAME_MAX
] = 0;
1173 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1183 PanicPid
= getppid();
1185 if (DefaultEsc
== -1)
1186 DefaultEsc
= Ctrl('a');
1187 if (DefaultMetaEsc
== -1)
1188 DefaultMetaEsc
= 'a';
1190 ap
= av0
+ strlen(av0
) - 1;
1193 if (!strncmp("screen", ap
, 6))
1195 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1207 if (dfp
&& dfp
!= stderr
)
1209 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1210 if ((dfp
= fopen(buf
, "w")) == NULL
)
1213 (void) chmod(buf
, 0666);
1218 if (attach_fd
== -1)
1220 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1221 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1228 freopen("/dev/null", "r", stdin
);
1229 freopen("/dev/null", "w", stdout
);
1234 freopen("/dev/null", "w", stderr
);
1235 debug("-- screen.back debug started\n");
1238 * This guarantees that the session owner is listed, even when we
1239 * start detached. From now on we should not refer to 'LoginName'
1240 * any more, use users->u_name instead.
1242 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1243 Panic(0, "Could not create user info");
1246 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1247 Panic(0, "Could not alloc display");
1250 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1251 debug1("D_encoding = %d\n", D_encoding
);
1257 /* user started us with -S option */
1258 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1262 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1265 for (ap
= socknamebuf
; *ap
; ap
++)
1269 if (strlen(socknamebuf
) > NAME_MAX
)
1271 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1272 socknamebuf
[NAME_MAX
] = 0;
1275 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1277 ServerSocket
= MakeServerSocket();
1280 # ifdef ALLOW_SYSSCREENRC
1281 if ((ap
= getenv("SYSSCREENRC")))
1282 (void)StartRc(ap
, 0);
1285 (void)StartRc(ETCSCREENRC
, 0);
1287 (void)StartRc(RcFileName
, 0);
1291 # endif /* UTNOKEEP */
1292 # endif /* UTMPOK */
1295 if (InitTermcap(0, 0))
1297 debug("Could not init termcap - exiting\n");
1298 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1301 Kill(D_userpid
, SIG_BYE
);
1304 MakeDefaultCanvas();
1316 signal(SIGHUP
, SigHup
);
1317 signal(SIGINT
, FinitHandler
);
1318 signal(SIGQUIT
, FinitHandler
);
1319 signal(SIGTERM
, FinitHandler
);
1321 signal(SIGTTIN
, SIG_IGN
);
1322 signal(SIGTTOU
, SIG_IGN
);
1328 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1329 /* Note: SetMode must be called _before_ FinishRc. */
1330 SetTTY(D_userfd
, &D_NewMode
);
1331 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1332 Msg(errno
, "Warning: NBLOCK fcntl failed");
1335 brktty(-1); /* just try */
1336 signal(SIGCHLD
, SigChld
);
1338 # ifdef ALLOW_SYSSCREENRC
1339 if ((ap
= getenv("SYSSCREENRC")))
1343 FinishRc(ETCSCREENRC
);
1345 FinishRc(RcFileName
);
1347 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1348 if (windows
== NULL
)
1350 debug("We open one default window, as screenrc did not specify one.\n");
1351 if (MakeWindow(&nwin
) == -1)
1353 Msg(0, "Sorry, could not find a PTY.");
1364 if (display
&& default_startup
)
1365 display_copyright();
1366 signal(SIGINT
, SigInt
);
1367 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1369 Msg(0, "New screen...");
1373 serv_read
.type
= EV_READ
;
1374 serv_read
.fd
= ServerSocket
;
1375 serv_read
.handler
= serv_read_fn
;
1378 serv_select
.pri
= -10;
1379 serv_select
.type
= EV_ALWAYS
;
1380 serv_select
.handler
= serv_select_fn
;
1381 evenq(&serv_select
);
1383 logflushev
.type
= EV_TIMEOUT
;
1384 logflushev
.handler
= logflush_fn
;
1392 WindowDied(p
, wstat
, wstat_valid
)
1399 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1400 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1403 if (ZombieKey_destroy
&& !killit
)
1405 char buf
[100], *s
, reason
[100];
1409 if (WIFEXITED(wstat
))
1410 if (WEXITSTATUS(wstat
))
1411 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1413 sprintf(reason
, "terminated normally");
1414 else if (WIFSIGNALED(wstat
))
1415 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1417 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1422 sprintf(reason
, "detached from window");
1427 s
[strlen(s
) - 1] = '\0';
1428 debug3("window %d (%s) going into zombie state fd %d",
1429 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1431 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1434 p
->w_slot
= 0; /* "detached" */
1439 p
->w_deadpid
= p
->w_pid
;
1442 /* p->w_y = p->w_bot; */
1443 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1444 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1445 WriteString(p
, buf
, strlen(buf
));
1446 WindowChanged(p
, 'f');
1467 signal(SIGCHLD
, SigChld
);
1470 if (stat(SockPath
, &st
) == -1)
1472 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1473 if (!RecoverSocket())
1475 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1479 debug1("'%s' reconstructed\n", SockPath
);
1482 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1488 debug("SigChld()\n");
1496 /* Hangup all displays */
1497 while ((display
= displays
) != 0)
1503 * the backend's Interrupt handler
1504 * we cannot insert the intrc directly, as we never know
1513 debug("SigInt()\n");
1514 if (fore
&& displays
)
1516 # if defined(TERMIO) || defined(POSIX)
1517 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1519 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1522 write(fore
->w_ptyfd
, &ibuf
, 1);
1525 signal(SIGINT
, SigInt
);
1526 debug("SigInt() careful\n");
1527 InterruptPlease
= 1;
1535 struct display
*disp
;
1538 #if defined(SYSVSIGS) && defined(SIGHASARG)
1539 signal(sigsig
, SIG_IGN
);
1545 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1547 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1549 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1551 #else /* SHADOWPW && !DEBUG */
1553 #endif /* SHADOWPW && !DEBUG */
1555 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1557 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1558 SetTTY(disp
->d_userfd
, &D_OldMode
);
1559 write(disp
->d_userfd
, buf
, strlen(buf
));
1560 Kill(disp
->d_userpid
, SIG_BYE
);
1562 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1563 Kill(getpid(), SIGKILL
);
1565 #else /* SHADOWPW && !DEBUG */
1567 #endif /* SHADOWPW && !DEBUG */
1575 struct win
*p
, *next
;
1584 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1588 * From: rouilj@sni-usa.com (John Rouillard)
1589 * note that WUNTRACED is not documented to work, but it is defined in
1590 * /usr/include/sys/wait.h, so it may work
1592 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1593 # else /* USE_WAIT2 */
1594 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1595 # endif /* USE_WAIT2 */
1598 while ((pid
= wait(&wstat
)) < 0)
1602 #endif /* BSDJOBS */
1604 for (p
= windows
; p
; p
= next
)
1607 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1608 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1610 /* child has ceased to exist */
1614 if (WIFSTOPPED(wstat
))
1616 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1618 if (WSTOPSIG(wstat
) == SIGTTIN
)
1620 Msg(0, "Suspended (tty input)");
1625 if (WSTOPSIG(wstat
) == SIGTTOU
)
1627 Msg(0, "Suspended (tty output)");
1631 /* Try to restart process */
1632 Msg(0, "Child has been stopped, restarting.");
1633 if (killpg(pid
, SIGCONT
))
1639 WindowDied(p
, wstat
, 1);
1644 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1646 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1654 debug1("pid %d not found - hope that's ok\n", pid
);
1661 FinitHandler SIGDEFARG
1664 debug1("FinitHandler called, sig %d.\n", sigsig
);
1666 debug("FinitHandler called.\n");
1676 signal(SIGCHLD
, SIG_DFL
);
1677 signal(SIGHUP
, SIG_IGN
);
1678 debug1("Finit(%d);\n", i
);
1681 struct win
*p
= windows
;
1682 windows
= windows
->w_next
;
1685 if (ServerSocket
!= -1)
1687 debug1("we unlink(%s)\n", SockPath
);
1692 (void) unlink(SockPath
);
1698 for (display
= displays
; display
; display
= display
->d_next
)
1706 AddStr("[screen is terminating]\r\n");
1708 SetTTY(D_userfd
, &D_OldMode
);
1709 fcntl(D_userfd
, F_SETFL
, 0);
1711 Kill(D_userpid
, SIG_BYE
);
1714 * we _cannot_ call eexit(i) here,
1715 * instead of playing with the Socket above. Sigh.
1725 if (ServerSocket
!= -1)
1727 debug1("we unlink(%s)\n", SockPath
);
1730 (void) unlink(SockPath
);
1740 debug1("Hangup %x\n", display
);
1746 if (auto_detach
|| displays
->d_next
)
1753 * Detach now has the following modes:
1754 *D_DETACH SIG_BYE detach backend and exit attacher
1755 *D_HANGUP SIG_BYE detach backend and exit attacher
1756 *D_STOP SIG_STOP stop attacher (and detach backend)
1757 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1758 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1759 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1760 *D_LOCK SIG_LOCK lock the attacher
1762 * we always remove our utmp slots. (even when "lock" or "stop")
1763 * Note: Take extra care here, we may be called by interrupt!
1776 signal(SIGHUP
, SIG_IGN
);
1777 debug1("Detach(%d)\n", mode
);
1789 AddStr("[detached]\r\n");
1797 #ifdef REMOTE_DETACH
1799 AddStr("[remote detached]\r\n");
1805 AddStr("[power detached]\r\n");
1806 if (PowDetachString
)
1808 AddStr(PowDetachString
);
1811 sign
= SIG_POWER_BYE
;
1813 #ifdef REMOTE_DETACH
1814 case D_REMOTE_POWER
:
1815 AddStr("[remote power detached]\r\n");
1816 if (PowDetachString
)
1818 AddStr(PowDetachString
);
1821 sign
= SIG_POWER_BYE
;
1828 /* tell attacher to lock terminal with a lockprg. */
1832 if (displays
->d_next
== 0)
1834 for (p
= windows
; p
; p
= p
->w_next
)
1836 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1840 * Set the slot to 0 to get the window
1843 p
->w_slot
= (slot_t
) 0;
1847 if (mode
!= D_HANGUP
)
1850 if (displays
->d_next
== 0 && console_window
)
1852 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1854 debug("could not release console - killing window\n");
1855 KillWindow(console_window
);
1856 display
= displays
; /* restore display */
1862 ReleaseAutoWritelock(display
, D_fore
);
1864 D_user
->u_detachwin
= D_fore
->w_number
;
1865 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1867 AutosaveLayout(D_layout
);
1868 layout_last
= D_layout
;
1869 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1871 p
= Layer2Window(cv
->c_layer
);
1872 SetCanvasWindow(cv
, 0);
1874 WindowChanged(p
, 'u');
1878 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1881 /* Flag detached-ness */
1884 * tell father what to do. We do that after we
1885 * freed the tty, thus getty feels more comfortable on hpux
1886 * if it was a power detach.
1889 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1890 debug("Detach returns, we are successfully detached.\n");
1891 signal(SIGHUP
, SigHup
);
1901 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1907 register char **op
, **np
;
1908 static char stybuf
[MAXSTR
];
1910 for (op
= environ
; *op
; ++op
)
1913 free((char *)NewEnv
);
1914 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1917 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1918 *np
++ = stybuf
; /* NewEnv[0] */
1919 *np
++ = Term
; /* NewEnv[1] */
1920 np
++; /* room for SHELL */
1922 np
+= 2; /* room for TERMCAP and WINDOW */
1924 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
1927 for (op
= environ
; *op
; ++op
)
1929 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
1930 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
1931 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
1932 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
1941 #if defined(USEVARARGS) && defined(__STDC__)
1942 Msg(int err
, char *fmt
, VA_DOTS
)
1944 Msg(err
, fmt
, VA_DOTS
)
1951 char buf
[MAXPATHLEN
*2];
1956 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
1963 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
1964 buf
[sizeof(buf
) - 1] = 0;
1966 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
1968 if (display
&& displays
)
1972 for (display
= displays
; display
; display
= display
->d_next
)
1977 /* no displays but a display - must have forked.
1978 * send message to backend!
1980 char *tty
= D_usertty
;
1981 struct display
*olddisplay
= display
;
1982 display
= 0; /* only send once */
1983 SendErrorMsg(tty
, buf
);
1984 display
= olddisplay
;
1987 printf("%s\r\n", buf
);
1991 * Call FinitTerm for all displays, write a message to each and call eexit();
1995 #if defined(USEVARARGS) && defined(__STDC__)
1996 Panic(int err
, char *fmt
, VA_DOTS
)
1998 Panic(err
, fmt
, VA_DOTS
)
2005 char buf
[MAXPATHLEN
*2];
2010 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2017 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2018 buf
[sizeof(buf
) - 1] = 0;
2020 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2021 if (displays
== 0 && display
== 0)
2023 printf("%s\r\n", buf
);
2025 Kill(PanicPid
, SIG_BYE
);
2027 else if (displays
== 0)
2029 /* no displays but a display - must have forked.
2030 * send message to backend!
2032 char *tty
= D_usertty
;
2034 SendErrorMsg(tty
, buf
);
2039 for (display
= displays
; display
; display
= display
->d_next
)
2048 SetTTY(D_userfd
, &D_OldMode
);
2049 fcntl(D_userfd
, F_SETFL
, 0);
2050 write(D_userfd
, buf
, strlen(buf
));
2051 write(D_userfd
, "\n", 1);
2054 Kill(D_userpid
, SIG_BYE
);
2057 if (tty_oldmode
>= 0)
2060 if (setuid(own_uid
))
2061 xseteuid(own_uid
); /* may be a loop. sigh. */
2065 debug1("Panic: changing back modes from %s\n", attach_tty
);
2066 chmod(attach_tty
, tty_oldmode
);
2074 * '^' is allowed as an escape mechanism for control characters. jw.
2076 * Added time insertion using ideas/code from /\ndy Jones
2077 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2082 static const char days
[] = "SunMonTueWedThuFriSat";
2083 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2086 static char winmsg_buf
[MAXSTR
];
2087 #define MAX_WINMSG_REND 16 /* rendition changes */
2088 static int winmsg_rend
[MAX_WINMSG_REND
];
2089 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2090 static int winmsg_numrend
;
2093 pad_expand(buf
, p
, numpad
, padlen
)
2102 padlen
= padlen
- (p
- buf
); /* space for rent */
2105 pn2
= pn
= p
+ padlen
;
2109 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2111 winmsg_rendpos
[--r
] = pn
- buf
;
2118 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2129 struct backtick
*next
;
2134 char result
[MAXSTR
];
2141 struct backtick
*backticks
;
2145 struct backtick
*bt
;
2150 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2154 if (c
>= ' ' || c
== '\005')
2161 backtick_fn(ev
, data
)
2165 struct backtick
*bt
;
2168 bt
= (struct backtick
*)data
;
2169 debug1("backtick_fn for #%d\n", bt
->num
);
2171 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2174 debug1("EOF on backtick #%d\n", bt
->num
);
2180 debug1("read %d bytes\n", l
);
2182 for (j
= 0; j
< l
; j
++)
2183 if (bt
->buf
[i
- j
- 1] == '\n')
2187 for (k
= i
- j
- 2; k
>= 0; k
--)
2188 if (bt
->buf
[k
] == '\n')
2191 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2192 bt
->result
[i
- j
- k
- 1] = 0;
2193 backtick_filter(bt
);
2194 WindowChanged(0, '`');
2196 if (j
== l
&& i
== MAXSTR
)
2204 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2211 setbacktick(num
, lifespan
, tick
, cmdv
)
2217 struct backtick
**btp
, *bt
;
2220 debug1("setbacktick called for backtick #%d\n", num
);
2221 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2228 for (v
= bt
->cmdv
; *v
; v
++)
2245 bt
= (struct backtick
*)malloc(sizeof *bt
);
2251 bzero(bt
, sizeof(*bt
));
2257 bt
->lifespan
= lifespan
;
2264 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2266 debug("setbacktick: continuous mode\n");
2267 bt
->buf
= (char *)malloc(MAXSTR
);
2271 setbacktick(num
, 0, 0, (char **)0);
2274 bt
->ev
.type
= EV_READ
;
2275 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2276 bt
->ev
.handler
= backtick_fn
;
2277 bt
->ev
.data
= (char *)bt
;
2284 runbacktick(bt
, tickp
, now
)
2285 struct backtick
*bt
;
2292 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2293 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2295 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2297 debug1("returning old result (%d)\n", bt
->lifespan
);
2300 f
= readpipe(bt
->cmdv
);
2304 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2306 debug1("runbacktick: read %d bytes\n", l
);
2308 for (j
= 1; j
< l
; j
++)
2309 if (bt
->result
[i
- j
- 1] == '\n')
2311 if (j
== l
&& i
== sizeof(bt
->result
))
2313 j
= sizeof(bt
->result
) / 2;
2318 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2323 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2324 if (i
&& bt
->result
[i
- 1] == '\n')
2326 debug1("runbacktick: finished, %d bytes\n", i
);
2328 backtick_filter(bt
);
2330 bt
->bestbefore
= now2
+ bt
->lifespan
;
2335 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2345 register char *p
= winmsg_buf
;
2355 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2362 struct backtick
*bt
;
2364 if (winmsg_numrend
>= 0)
2367 winmsg_numrend
= -winmsg_numrend
;
2372 gettimeofday(&now
, NULL
);
2373 for (; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2379 if (*s
!= '^' && *s
>= 64)
2404 if (*++s
== esc
) /* double escape ? */
2406 if ((plusflg
= *s
== '+') != 0)
2408 if ((minusflg
= *s
== '-') != 0)
2410 if ((zeroflg
= *s
== '0') != 0)
2413 while(*s
>= '0' && *s
<= '9')
2414 num
= num
* 10 + (*s
++ - '0');
2415 if ((longflg
= *s
== 'L') != 0)
2423 if ((!qmflag
&& !omflag
) || omflag
== 1)
2426 if (qmnumrend
< winmsg_numrend
)
2427 winmsg_numrend
= qmnumrend
;
2433 qmnumrend
= winmsg_numrend
;
2434 qmflag
= omflag
= 0;
2440 if (qmflag
&& omflag
!= 1)
2444 qmnumrend
= winmsg_numrend
;
2449 if (qmnumrend
< winmsg_numrend
)
2450 winmsg_numrend
= qmnumrend
;
2454 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2455 case 'a': case 'A': case 's': case 'c': case 'C':
2460 time_t nowsec
= now
.tv_sec
;
2461 tm
= localtime(&nowsec
);
2464 if (!tick
|| tick
> 3600)
2469 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2473 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2475 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2479 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2483 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2485 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2489 sprintf(p
, "%02d", tm
->tm_year
% 100);
2492 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2495 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2498 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2501 sprintf(p
, "%02d", tm
->tm_sec
);
2505 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2506 if (!tick
|| tick
> 60)
2510 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2511 if (!tick
|| tick
> 60)
2531 if (!tick
|| tick
> 60)
2540 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2547 for (bt
= backticks
; bt
; bt
= bt
->next
)
2557 char savebuf
[sizeof(winmsg_buf
)];
2559 int oldnumrend
= winmsg_numrend
;
2562 strcpy(savebuf
, winmsg_buf
);
2563 winmsg_numrend
= -winmsg_numrend
;
2564 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2565 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2566 if (!tick
|| oldtick
< tick
)
2568 if ((int)strlen(winmsg_buf
) < l
)
2569 strcat(savebuf
, winmsg_buf
);
2570 strcpy(winmsg_buf
, savebuf
);
2571 while (oldnumrend
< winmsg_numrend
)
2572 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2581 struct win
*oldfore
= 0;
2589 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2602 AddOtherUsers(p
, l
- 1, win
);
2610 AddWindowFlags(p
, l
- 1, win
);
2617 if (win
&& (int)strlen(win
->w_title
) < l
)
2619 strcpy(p
, win
->w_title
);
2629 for (i
= 0; i
< 127; i
++)
2630 if (s
[i
] && s
[i
] != '}')
2634 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2638 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2639 if (i
!= 1 || rbuf
[0] != '-')
2640 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2641 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2643 winmsg_rend
[winmsg_numrend
] = r
;
2644 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2654 if ((int)strlen(HostName
) < l
)
2656 strcpy(p
, HostName
);
2665 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2666 minusflg
= !minusflg
;
2671 truncpos
= p
- winmsg_buf
;
2672 truncper
= num
> 100 ? 100 : num
;
2673 trunclong
= longflg
;
2679 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2681 /* expand all pads */
2684 num
= (plusflg
? lastpad
: padlen
) - num
;
2685 if (!plusflg
&& padlen
== 0)
2686 num
= p
- winmsg_buf
;
2691 if (*s
!= '=' && num
== 0 && !plusflg
)
2696 num
= p
- winmsg_buf
;
2698 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2704 if (num
> MAXSTR
- 1)
2707 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2709 if (p
- winmsg_buf
> num
&& !longflg
)
2718 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2721 if (trunc
< lastpad
)
2723 left
= truncpos
- trunc
;
2724 if (left
> p
- winmsg_buf
- num
)
2725 left
= p
- winmsg_buf
- num
;
2726 debug1("lastpad = %d, ", lastpad
);
2727 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2730 if (left
+ lastpad
> p
- winmsg_buf
)
2731 left
= p
- winmsg_buf
- lastpad
;
2732 if (p
- winmsg_buf
- lastpad
- left
> 0)
2733 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2736 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2739 winmsg_rendpos
[r
] -= left
;
2740 if (winmsg_rendpos
[r
] < lastpad
)
2741 winmsg_rendpos
[r
] = lastpad
;
2745 if (p
- winmsg_buf
> lastpad
)
2746 winmsg_buf
[lastpad
] = '.';
2747 if (p
- winmsg_buf
> lastpad
+ 1)
2748 winmsg_buf
[lastpad
+ 1] = '.';
2749 if (p
- winmsg_buf
> lastpad
+ 2)
2750 winmsg_buf
[lastpad
+ 2] = '.';
2753 if (p
- winmsg_buf
> num
)
2755 p
= winmsg_buf
+ num
;
2758 if (num
- 1 >= lastpad
)
2760 if (num
- 2 >= lastpad
)
2762 if (num
- 3 >= lastpad
)
2766 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2767 winmsg_rendpos
[--r
] = num
;
2771 if (lastpad
> p
- winmsg_buf
)
2772 lastpad
= p
- winmsg_buf
;
2773 debug1("lastpad now %d\n", lastpad
);
2777 while (p
- winmsg_buf
< num
)
2779 lastpad
= p
- winmsg_buf
;
2782 debug1("lastpad2 now %d\n", lastpad
);
2788 *p
= 127; /* internal pad representation */
2802 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2804 sprintf(p
, "%*d", num
, win
->w_number
);
2811 if (qmpos
&& !qmflag
)
2816 if (padlen
> MAXSTR
- 1)
2817 padlen
= MAXSTR
- 1;
2818 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2822 evdeq(ev
); /* just in case */
2823 ev
->timeout
.tv_sec
= 0;
2824 ev
->timeout
.tv_usec
= 0;
2828 now
.tv_usec
= 100000;
2832 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2834 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2840 MakeWinMsg(s
, win
, esc
)
2845 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2849 PutWinMsg(s
, start
, max
)
2855 struct mchar rendstack
[MAX_WINMSG_REND
];
2858 if (s
!= winmsg_buf
)
2860 /* sorry, no fancy coloring available */
2861 debug1("PutWinMsg %s plain\n", s
);
2874 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
2875 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
2877 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
2879 if (p
< winmsg_rendpos
[i
])
2881 n
= winmsg_rendpos
[i
] - p
;
2898 rend
= rendstack
[--rendstackn
];
2902 rendstack
[rendstackn
++] = rend
;
2903 ApplyAttrColor(r
, &rend
);
2905 SetRendition(&rend
);
2933 if ((j
= open("/dev/null", 0)) >= 0)
2940 while (dup(++i
) < 0 && errno
!= EBADF
)
2942 debug1(" [%d]\n", i
);
2955 serv_read_fn(ev
, data
)
2959 debug("Knock - knock!\n");
2964 serv_select_fn(ev
, data
)
2970 debug("serv_select_fn called\n");
2971 /* XXX: messages?? */
2976 if (InterruptPlease
)
2978 debug("Backend received interrupt\n");
2979 /* This approach is rather questionable in a multi-display
2981 if (fore
&& displays
)
2983 #if defined(TERMIO) || defined(POSIX)
2984 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
2986 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
2989 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
2991 debug1("Backend wrote interrupt to %d", fore
->w_number
);
2992 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
2994 write(fore
->w_ptyfd
, &ibuf
, 1);
2995 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
2998 InterruptPlease
= 0;
3001 for (p
= windows
; p
; p
= p
->w_next
)
3003 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3006 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3007 p
->w_bell
= BELL_ON
;
3008 for (display
= displays
; display
; display
= display
->d_next
)
3010 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3011 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3015 p
->w_bell
= BELL_DONE
;
3016 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3018 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3020 Msg(0, "%s", VisualBellString
);
3024 debug1("using vbell timeout %d\n", VBellWait
);
3025 SetTimeout(&D_statusev
, VBellWait
);
3029 /* don't annoy the user with two messages */
3030 if (p
->w_monitor
== MON_FOUND
)
3031 p
->w_monitor
= MON_DONE
;
3032 WindowChanged(p
, 'f');
3034 if (p
->w_monitor
== MON_FOUND
)
3037 p
->w_monitor
= MON_ON
;
3038 for (display
= displays
; display
; display
= display
->d_next
)
3040 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3041 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3044 continue; /* user already sees window */
3046 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3047 continue; /* user doesn't care */
3049 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3050 p
->w_monitor
= MON_DONE
;
3052 WindowChanged(p
, 'f');
3056 for (display
= displays
; display
; display
= display
->d_next
)
3059 if (D_status
== STATUS_ON_WIN
)
3061 /* XXX: should use display functions! */
3062 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3066 /* normalize window, see resize.c */
3067 lx
= cv
->c_layer
->l_x
;
3068 ly
= cv
->c_layer
->l_y
;
3069 if (lx
== cv
->c_layer
->l_width
)
3071 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3073 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3074 cv
->c_yoff
= cv
->c_ys
- ly
;
3075 RethinkViewportOffsets(cv
);
3076 if (n
> cv
->c_layer
->l_height
)
3077 n
= cv
->c_layer
->l_height
;
3079 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3080 LayRedisplayLine(-1, -1, -1, 1);
3081 for (i
= 0; i
< n
; i
++)
3082 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3083 if (cv
== cv
->c_display
->d_forecv
)
3087 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3089 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3090 cv
->c_yoff
= cv
->c_ye
- ly
;
3091 RethinkViewportOffsets(cv
);
3092 if (n
> cv
->c_layer
->l_height
)
3093 n
= cv
->c_layer
->l_height
;
3095 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3096 LayRedisplayLine(-1, -1, -1, 1);
3097 for (i
= 0; i
< n
; i
++)
3098 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3099 if (cv
== cv
->c_display
->d_forecv
)
3103 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3105 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3106 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3107 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3108 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3109 n
= cv
->c_xs
- cv
->c_xoff
;
3111 RethinkViewportOffsets(cv
);
3112 if (n
> cv
->c_layer
->l_width
)
3113 n
= cv
->c_layer
->l_width
;
3115 LayRedisplayLine(-1, -1, -1, 1);
3116 for (i
= 0; i
< flayer
->l_height
; i
++)
3118 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3119 LayRedisplayLine(i
, 0, n
- 1, 1);
3121 if (cv
== cv
->c_display
->d_forecv
)
3125 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3127 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3128 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3129 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3130 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3131 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3133 RethinkViewportOffsets(cv
);
3134 if (n
> cv
->c_layer
->l_width
)
3135 n
= cv
->c_layer
->l_width
;
3137 LayRedisplayLine(-1, -1, -1, 1);
3138 for (i
= 0; i
< flayer
->l_height
; i
++)
3140 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3141 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3143 if (cv
== cv
->c_display
->d_forecv
)
3150 for (display
= displays
; display
; display
= display
->d_next
)
3152 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3154 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3155 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3160 logflush_fn(ev
, data
)
3168 if (!islogfile(NULL
))
3169 return; /* no more logfiles */
3171 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3174 SetTimeout(ev
, n
* 1000);
3175 evenq(ev
); /* re-enqueue ourself */
3179 /* write fancy time-stamp */
3180 for (p
= windows
; p
; p
= p
->w_next
)
3184 p
->w_logsilence
+= n
;
3185 if (p
->w_logsilence
< logtstamp_after
)
3187 if (p
->w_logsilence
- n
>= logtstamp_after
)
3189 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3190 logfwrite(p
->w_log
, buf
, strlen(buf
));
3195 * Interprets ^?, ^@ and other ^-control-char notation.
3196 * Interprets \ddd octal notation
3198 * The result is placed in *cp, p is advanced behind the parsed expression and
3207 if (*p
== '^' && p
[1])
3217 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3221 *cp
= *cp
* 8 + *p
- '0';
3222 while (*++p
<= '7' && *p
>= '0');
3233 unsigned char buf
[2];
3236 SetEscape((struct acluser
*)0, -1, -1);
3239 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3240 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3242 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);