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 */
347 char socknamebuf
[2 * MAXSTR
];
349 char *myname
= (ac
== 0) ? "screen" : av
[0];
352 #ifdef _MODE_T /* (jw) */
357 #if defined(SYSV) && !defined(ISC)
358 struct utsname utsnam
;
360 struct NewWindow nwin
;
361 int detached
= 0; /* start up detached */
365 char *script_file
= 0;
368 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
369 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
371 #if defined(sun) && defined(SVR4)
373 /* Solaris' login blocks SIGHUP! This is _very bad_ */
376 sigprocmask(SIG_SETMASK
, &sset
, 0);
381 * First, close all unused descriptors
382 * (otherwise, we might have problems with the select() call)
388 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
389 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
390 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
391 debug2("-- screen debug started %s (%s)\n", *av
, version
);
405 debug("NAMEDPIPE\n");
407 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
408 debug("Window size changing enabled\n");
438 debug1("NAME_MAX = %d\n", NAME_MAX
);
441 BellString
= SaveStr("Bell in window %n");
442 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
443 ActivityString
= SaveStr("Activity in window %n");
444 screenlogfile
= SaveStr("screenlog.%n");
445 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
446 hstatusstring
= SaveStr("%h");
447 captionstring
= SaveStr("%3n %t");
448 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
449 wlisttit
= SaveStr("Num Name%=Flags");
450 wliststr
= SaveStr("%3n %t%=%f");
452 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
458 default_startup
= (ac
> 1) ? 0 : 1;
460 VBellWait
= VBELLWAIT
* 1000;
461 MsgWait
= MSGWAIT
* 1000;
462 MsgMinWait
= MSGMINWAIT
* 1000;
463 SilenceWait
= SILENCEWAIT
;
468 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
469 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
473 CompileKeys((char *)0, 0, mark_key_tab
);
477 screenencodings
= SaveStr(SCREENENCODINGS
);
483 nwin_options
= nwin_undef
;
484 strcpy(screenterm
, "screen");
486 logreopen_register(lf_secreopen
);
489 /* if this is a login screen, assume -RR */
498 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
503 if (--ac
> 0 && *ap
== '-')
505 if (ap
[1] == '-' && ap
[2] == 0)
511 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
512 Panic(0, "Screen version %s", version
);
513 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
514 exit_with_usage(myname
, NULL
, NULL
);
515 while (ap
&& *ap
&& *++ap
)
520 nwin_options
.aflag
= 1;
525 case 'p': /* preselect */
531 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
538 bd
.bd_start_braille
= 1;
547 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
556 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
560 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
569 nwin_options
.flowflag
= FLOW_NOW
* 0;
576 nwin_options
.flowflag
= FLOW_NOW
* 1;
579 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
582 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
587 exit_with_usage(myname
, NULL
, NULL
);
588 nwin_options
.histheight
= atoi(*++av
);
589 if (nwin_options
.histheight
< 0)
590 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
595 case 't': /* title, the former AkA == -k */
597 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
598 nwin_options
.aka
= *++av
;
606 nwin_options
.lflag
= 0;
613 nwin_options
.lflag
= 1;
616 nwin_options
.lflag
= 3;
619 case 'i': /* -list */
621 if (ac
> 1 && !SockMatch
)
629 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
635 if (ac
> 1 && !SockMatch
)
642 nwin_options
.Lflag
= 1;
647 case 'O': /* to be (or not to be?) deleted. jw. */
652 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
653 if (strlen(*++av
) < 20)
654 strcpy(screenterm
, *av
);
656 Panic(0, "-T: terminal name too long. (max. 20 char)");
657 nwin_options
.term
= screenterm
;
667 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
671 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
679 rflag
+= (*ap
== 'R') ? 2 : 1;
690 if (*av
[1] != '-' && !SockMatch
)
694 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
701 exit_with_usage(myname
, "Specify shell with -s", NULL
);
704 ShellProg
= SaveStr(*++av
);
705 debug1("ShellProg: '%s'\n", ShellProg
);
711 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
715 exit_with_usage(myname
, "Empty session-name?", NULL
);
721 Panic(0, "Screen version %s", version
);
725 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
730 exit_with_usage(myname
, "Specify lua script file with -u", NULL
);
733 script_file
= SaveStr(*++av
);
736 exit_with_usage(myname
, "Unknown option %s", --ap
);
748 if (eff_uid
!= real_uid
)
750 /* if running with s-bit, we must install a special signal
751 * handler routine that resets the s-bit, so that we get a
754 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
755 signal(SIGBUS
, CoreDump
);
757 signal(SIGSEGV
, CoreDump
);
761 setlocale(LC_ALL
, "");
764 if (nwin_options
.encoding
== -1)
766 /* ask locale if we should start in UTF-8 mode */
767 # ifdef HAVE_NL_LANGINFO
769 setlocale(LC_CTYPE
, "");
771 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
772 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
776 if (((s
= getenv("LC_ALL")) || (s
= getenv("LC_CTYPE")) ||
777 (s
= getenv("LANG"))) && InStr(s
, "UTF-8"))
778 nwin_options
.encoding
= UTF8
;
780 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
786 if((s
= getenv("LC_ALL")) || (s
= getenv("LC_CTYPE")) ||
787 (s
= getenv("LANG")))
789 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
797 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
798 Panic(0, "Ridiculously long socketname - try again.");
799 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
801 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
805 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
810 /* make the write() calls return -1 on all errors */
813 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
814 * It appears that in System V Release 4, UNIX, if you are writing
815 * an output file and you exceed the currently set file size limit,
816 * you _don't_ just get the call to `write' returning with a
817 * failure code. Rather, you get a signal called `SIGXFSZ' which,
818 * if neither handled nor ignored, will cause your program to crash
821 signal(SIGXFSZ
, SIG_IGN
);
825 signal(SIGPIPE
, SIG_IGN
);
832 sh
= getenv("SHELL");
833 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
835 ShellArgs
[0] = ShellProg
;
836 home
= getenv("HOME");
837 if (!mflag
&& !SockMatch
)
840 if (sty
&& *sty
== 0)
845 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
847 char nethackrc
[MAXPATHLEN
];
849 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
851 sprintf(nethackrc
,"%s/.nethackrc", home
);
852 nethackflag
= !access(nethackrc
, F_OK
);
858 own_uid
= multi_uid
= real_uid
;
859 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
862 Panic(0, "Must run suid root for multiuser support.");
865 SockMatch
= sockp
+ 1;
869 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
870 Panic(0, "Cannot identify account '%s'.", multi
);
871 multi_uid
= mppp
->pw_uid
;
872 multi_home
= SaveStr(mppp
->pw_dir
);
873 if (strlen(multi_home
) > MAXPATHLEN
- 10)
874 Panic(0, "home directory path too long");
876 /* always fake multi attach mode */
884 if (SockMatch
&& *SockMatch
== 0)
886 #endif /* MULTIUSER */
888 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
890 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
891 if ((int)ppp
->pw_uid
!= real_uid
)
892 ppp
= (struct passwd
*) 0;
896 if ((ppp
= getpwuid(real_uid
)) == 0)
898 Panic(0, "getpwuid() can't identify your account!");
901 LoginName
= ppp
->pw_name
;
903 LoginName
= SaveStr(LoginName
);
905 ppp
= getpwbyname(LoginName
, ppp
);
907 #if !defined(SOCKDIR) && defined(MULTIUSER)
908 if (multi
&& !multiattach
)
910 if (home
&& strcmp(home
, ppp
->pw_dir
))
911 Panic(0, "$HOME must match passwd entry for multiuser screens.");
915 #define SET_GUID() do \
919 eff_uid = real_uid; \
920 eff_gid = real_gid; \
923 #define SET_TTYNAME(fatal) do \
925 if (!(attach_tty = ttyname(0))) \
928 Panic(0, "Must be connected to a terminal."); \
932 else if (stat(attach_tty, &st)) \
933 Panic(errno, "Cannot access '%s'", attach_tty); \
934 if (strlen(attach_tty) >= MAXPATHLEN) \
935 Panic(0, "TtyName too long - sorry."); \
938 if (home
== 0 || *home
== '\0')
940 if (strlen(LoginName
) > 20)
941 Panic(0, "LoginName too long - sorry.");
943 if (multi
&& strlen(multi
) > 20)
944 Panic(0, "Screen owner name too long - sorry.");
946 if (strlen(home
) > MAXPATHLEN
- 25)
947 Panic(0, "$HOME too long - sorry.");
950 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
))
956 /* ttyname implies isatty */
959 tty_mode
= (int)st
.st_mode
& 0777;
963 fl
= fcntl(0, F_GETFL
, 0);
964 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
969 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
970 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
973 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
975 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
976 Panic(0, "Please set a terminal type.");
977 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
978 Panic(0, "$TERM too long - sorry.");
979 GetTTY(0, &attach_Mode
);
980 #ifdef DEBUGGGGGGGGGGGGGGG
981 DebugTTY(&attach_Mode
);
986 oumask
= umask(0); /* well, unsigned never fails? jw. */
988 if ((oumask
= (int)umask(0)) == -1)
989 Panic(errno
, "Cannot change umask to zero");
991 SockDir
= getenv("SCREENDIR");
994 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
995 Panic(0, "Ridiculously long $SCREENDIR - try again.");
998 Panic(0, "No $SCREENDIR with multi screens, please.");
1005 sprintf(SockPath
, "%s/.screen", multi_home
);
1009 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1018 sprintf(SockPath
, "%s/.screen", home
);
1024 if (access(SockDir
, F_OK
))
1026 debug1("SockDir '%s' missing ...\n", SockDir
);
1027 if (UserContext() > 0)
1029 if (mkdir(SockDir
, 0700))
1033 if (UserStatus() <= 0)
1034 Panic(0, "Cannot make directory '%s'.", SockDir
);
1036 if (SockDir
!= SockPath
)
1037 strcpy(SockPath
, SockDir
);
1043 if (lstat(SockDir
, &st
))
1045 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1046 (eff_gid
!= real_gid
) ? 0775 :
1052 if (mkdir(SockDir
, n
) == -1)
1053 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1057 if (!S_ISDIR(st
.st_mode
))
1058 Panic(0, "'%s' must be a directory.", SockDir
);
1059 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1060 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1061 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1062 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1064 if (((int)st
.st_mode
& 0777) != n
)
1065 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1067 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1068 if (access(SockPath
, F_OK
))
1070 if (mkdir(SockPath
, 0700) == -1)
1071 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1072 (void) chown(SockPath
, real_uid
, real_gid
);
1078 if (stat(SockPath
, &st
) == -1)
1079 Panic(errno
, "Cannot access %s", SockPath
);
1081 if (!S_ISDIR(st
.st_mode
))
1082 Panic(0, "%s is not a directory.", SockPath
);
1086 if ((int)st
.st_uid
!= multi_uid
)
1087 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1092 if ((int)st
.st_uid
!= real_uid
)
1093 Panic(0, "You are not the owner of %s.", SockPath
);
1095 if ((st
.st_mode
& 0777) != 0700)
1096 Panic(0, "Directory %s must have mode 700.", SockPath
);
1097 if (SockMatch
&& index(SockMatch
, '/'))
1098 Panic(0, "Bad session name '%s'", SockMatch
);
1099 SockName
= SockPath
+ strlen(SockPath
) + 1;
1101 (void) umask(oumask
);
1102 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1104 #if defined(SYSV) && !defined(ISC)
1105 if (uname(&utsnam
) == -1)
1106 Panic(errno
, "uname");
1107 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1108 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1110 (void) gethostname(HostName
, MAXSTR
);
1111 HostName
[MAXSTR
- 1] = '\0';
1113 if ((ap
= index(HostName
, '.')) != NULL
)
1122 real_uid
= multi_uid
;
1125 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1127 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1129 Panic(0, "No Sockets found in %s.\n", SockPath
);
1130 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1133 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1136 /* attach_tty is not mandatory */
1139 Panic(0, "Please specify a command.");
1141 SendCmdMessage(sty
, SockMatch
, av
);
1144 else if (rflag
|| xflag
)
1146 debug("screen -r: - is there anybody out there?\n");
1147 if (Attach(MSG_ATTACH
))
1154 Panic(0, "Can't create sessions of other users.");
1156 debug("screen -r: backend not responding -- still crying\n");
1158 else if (dflag
&& !mflag
)
1160 (void) Attach(MSG_DETACH
);
1161 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1165 if (!SockMatch
&& !mflag
&& sty
)
1167 /* attach_tty is not mandatory */
1170 nwin_options
.args
= av
;
1171 SendCreateMsg(sty
, &nwin
);
1175 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1177 if (!detached
|| dflag
!= 2)
1185 Panic(errno
, "fork");
1193 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1195 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1196 for (ap
= socknamebuf
; *ap
; ap
++)
1200 if (strlen(socknamebuf
) > NAME_MAX
)
1201 socknamebuf
[NAME_MAX
] = 0;
1203 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1210 PanicPid
= getppid();
1212 if (DefaultEsc
== -1)
1213 DefaultEsc
= Ctrl('a');
1214 if (DefaultMetaEsc
== -1)
1215 DefaultMetaEsc
= 'a';
1217 ap
= av0
+ strlen(av0
) - 1;
1220 if (!strncmp("screen", ap
, 6))
1222 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1234 if (dfp
&& dfp
!= stderr
)
1236 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1237 if ((dfp
= fopen(buf
, "w")) == NULL
)
1240 (void) chmod(buf
, 0666);
1245 if (attach_fd
== -1)
1247 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1248 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1255 freopen("/dev/null", "r", stdin
);
1256 freopen("/dev/null", "w", stdout
);
1261 freopen("/dev/null", "w", stderr
);
1262 debug("-- screen.back debug started\n");
1265 * This guarantees that the session owner is listed, even when we
1266 * start detached. From now on we should not refer to 'LoginName'
1267 * any more, use users->u_name instead.
1269 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1270 Panic(0, "Could not create user info");
1273 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1274 Panic(0, "Could not alloc display");
1277 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1278 debug1("D_encoding = %d\n", D_encoding
);
1284 /* user started us with -S option */
1285 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1289 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1292 for (ap
= socknamebuf
; *ap
; ap
++)
1296 if (strlen(socknamebuf
) > NAME_MAX
)
1298 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1299 socknamebuf
[NAME_MAX
] = 0;
1302 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1304 ServerSocket
= MakeServerSocket();
1311 ScriptSource(script_file
);
1317 # ifdef ALLOW_SYSSCREENRC
1318 if ((ap
= getenv("SYSSCREENRC")))
1319 (void)StartRc(ap
, 0);
1322 (void)StartRc(ETCSCREENRC
, 0);
1324 (void)StartRc(RcFileName
, 0);
1328 # endif /* UTNOKEEP */
1329 # endif /* UTMPOK */
1332 if (InitTermcap(0, 0))
1334 debug("Could not init termcap - exiting\n");
1335 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1338 Kill(D_userpid
, SIG_BYE
);
1341 MakeDefaultCanvas();
1353 signal(SIGHUP
, SigHup
);
1354 signal(SIGINT
, FinitHandler
);
1355 signal(SIGQUIT
, FinitHandler
);
1356 signal(SIGTERM
, FinitHandler
);
1358 signal(SIGTTIN
, SIG_IGN
);
1359 signal(SIGTTOU
, SIG_IGN
);
1365 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1366 /* Note: SetMode must be called _before_ FinishRc. */
1367 SetTTY(D_userfd
, &D_NewMode
);
1368 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1369 Msg(errno
, "Warning: NBLOCK fcntl failed");
1372 brktty(-1); /* just try */
1373 signal(SIGCHLD
, SigChld
);
1375 # ifdef ALLOW_SYSSCREENRC
1376 if ((ap
= getenv("SYSSCREENRC")))
1380 FinishRc(ETCSCREENRC
);
1382 FinishRc(RcFileName
);
1384 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1385 if (windows
== NULL
)
1387 debug("We open one default window, as screenrc did not specify one.\n");
1388 if (MakeWindow(&nwin
) == -1)
1390 Msg(0, "Sorry, could not find a PTY.");
1401 if (display
&& default_startup
)
1402 display_copyright();
1403 signal(SIGINT
, SigInt
);
1404 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1406 Msg(0, "New screen...");
1410 serv_read
.type
= EV_READ
;
1411 serv_read
.fd
= ServerSocket
;
1412 serv_read
.handler
= serv_read_fn
;
1415 serv_select
.pri
= -10;
1416 serv_select
.type
= EV_ALWAYS
;
1417 serv_select
.handler
= serv_select_fn
;
1418 evenq(&serv_select
);
1420 logflushev
.type
= EV_TIMEOUT
;
1421 logflushev
.handler
= logflush_fn
;
1429 WindowDied(p
, wstat
, wstat_valid
)
1436 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1437 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1440 if (ZombieKey_destroy
&& !killit
)
1442 char buf
[100], *s
, reason
[100];
1446 if (WIFEXITED(wstat
))
1447 if (WEXITSTATUS(wstat
))
1448 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1450 sprintf(reason
, "terminated normally");
1451 else if (WIFSIGNALED(wstat
))
1452 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1454 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1459 sprintf(reason
, "detached from window");
1464 s
[strlen(s
) - 1] = '\0';
1465 debug3("window %d (%s) going into zombie state fd %d",
1466 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1468 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1471 p
->w_slot
= 0; /* "detached" */
1476 p
->w_deadpid
= p
->w_pid
;
1479 /* p->w_y = p->w_bot; */
1480 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1481 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1482 WriteString(p
, buf
, strlen(buf
));
1483 WindowChanged(p
, 'f');
1504 signal(SIGCHLD
, SigChld
);
1507 if (stat(SockPath
, &st
) == -1)
1509 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1510 if (!RecoverSocket())
1512 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1516 debug1("'%s' reconstructed\n", SockPath
);
1519 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1525 debug("SigChld()\n");
1533 /* Hangup all displays */
1534 while ((display
= displays
) != 0)
1540 * the backend's Interrupt handler
1541 * we cannot insert the intrc directly, as we never know
1550 debug("SigInt()\n");
1551 if (fore
&& displays
)
1553 # if defined(TERMIO) || defined(POSIX)
1554 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1556 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1559 write(fore
->w_ptyfd
, &ibuf
, 1);
1562 signal(SIGINT
, SigInt
);
1563 debug("SigInt() careful\n");
1564 InterruptPlease
= 1;
1572 struct display
*disp
;
1575 #if defined(SYSVSIGS) && defined(SIGHASARG)
1576 signal(sigsig
, SIG_IGN
);
1582 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1584 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1586 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1588 #else /* SHADOWPW && !DEBUG */
1590 #endif /* SHADOWPW && !DEBUG */
1592 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1594 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1595 SetTTY(disp
->d_userfd
, &D_OldMode
);
1596 write(disp
->d_userfd
, buf
, strlen(buf
));
1597 Kill(disp
->d_userpid
, SIG_BYE
);
1599 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1600 Kill(getpid(), SIGKILL
);
1602 #else /* SHADOWPW && !DEBUG */
1604 #endif /* SHADOWPW && !DEBUG */
1612 struct win
*p
, *next
;
1621 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1625 * From: rouilj@sni-usa.com (John Rouillard)
1626 * note that WUNTRACED is not documented to work, but it is defined in
1627 * /usr/include/sys/wait.h, so it may work
1629 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1630 # else /* USE_WAIT2 */
1631 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1632 # endif /* USE_WAIT2 */
1635 while ((pid
= wait(&wstat
)) < 0)
1639 #endif /* BSDJOBS */
1641 for (p
= windows
; p
; p
= next
)
1644 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1645 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1647 /* child has ceased to exist */
1651 if (WIFSTOPPED(wstat
))
1653 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1655 if (WSTOPSIG(wstat
) == SIGTTIN
)
1657 Msg(0, "Suspended (tty input)");
1662 if (WSTOPSIG(wstat
) == SIGTTOU
)
1664 Msg(0, "Suspended (tty output)");
1668 /* Try to restart process */
1669 Msg(0, "Child has been stopped, restarting.");
1670 if (killpg(pid
, SIGCONT
))
1676 WindowDied(p
, wstat
, 1);
1681 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1683 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1691 debug1("pid %d not found - hope that's ok\n", pid
);
1698 FinitHandler SIGDEFARG
1701 debug1("FinitHandler called, sig %d.\n", sigsig
);
1703 debug("FinitHandler called.\n");
1713 signal(SIGCHLD
, SIG_DFL
);
1714 signal(SIGHUP
, SIG_IGN
);
1715 debug1("Finit(%d);\n", i
);
1721 struct win
*p
= windows
;
1722 windows
= windows
->w_next
;
1725 if (ServerSocket
!= -1)
1727 debug1("we unlink(%s)\n", SockPath
);
1732 (void) unlink(SockPath
);
1738 for (display
= displays
; display
; display
= display
->d_next
)
1746 AddStr("[screen is terminating]\r\n");
1748 SetTTY(D_userfd
, &D_OldMode
);
1749 fcntl(D_userfd
, F_SETFL
, 0);
1751 Kill(D_userpid
, SIG_BYE
);
1754 * we _cannot_ call eexit(i) here,
1755 * instead of playing with the Socket above. Sigh.
1765 if (ServerSocket
!= -1)
1767 debug1("we unlink(%s)\n", SockPath
);
1770 (void) unlink(SockPath
);
1780 debug1("Hangup %x\n", display
);
1786 if (auto_detach
|| displays
->d_next
)
1793 * Detach now has the following modes:
1794 *D_DETACH SIG_BYE detach backend and exit attacher
1795 *D_HANGUP SIG_BYE detach backend and exit attacher
1796 *D_STOP SIG_STOP stop attacher (and detach backend)
1797 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1798 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1799 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1800 *D_LOCK SIG_LOCK lock the attacher
1802 * we always remove our utmp slots. (even when "lock" or "stop")
1803 * Note: Take extra care here, we may be called by interrupt!
1816 signal(SIGHUP
, SIG_IGN
);
1817 debug1("Detach(%d)\n", mode
);
1829 AddStr("[detached]\r\n");
1837 #ifdef REMOTE_DETACH
1839 AddStr("[remote detached]\r\n");
1845 AddStr("[power detached]\r\n");
1846 if (PowDetachString
)
1848 AddStr(PowDetachString
);
1851 sign
= SIG_POWER_BYE
;
1853 #ifdef REMOTE_DETACH
1854 case D_REMOTE_POWER
:
1855 AddStr("[remote power detached]\r\n");
1856 if (PowDetachString
)
1858 AddStr(PowDetachString
);
1861 sign
= SIG_POWER_BYE
;
1868 /* tell attacher to lock terminal with a lockprg. */
1872 if (displays
->d_next
== 0)
1874 for (p
= windows
; p
; p
= p
->w_next
)
1876 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1880 * Set the slot to 0 to get the window
1883 p
->w_slot
= (slot_t
) 0;
1887 if (mode
!= D_HANGUP
)
1890 if (displays
->d_next
== 0 && console_window
)
1892 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1894 debug("could not release console - killing window\n");
1895 KillWindow(console_window
);
1896 display
= displays
; /* restore display */
1902 ReleaseAutoWritelock(display
, D_fore
);
1904 D_user
->u_detachwin
= D_fore
->w_number
;
1905 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1907 AutosaveLayout(D_layout
);
1908 layout_last
= D_layout
;
1909 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1911 p
= Layer2Window(cv
->c_layer
);
1912 SetCanvasWindow(cv
, 0);
1914 WindowChanged(p
, 'u');
1918 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1921 /* Flag detached-ness */
1924 * tell father what to do. We do that after we
1925 * freed the tty, thus getty feels more comfortable on hpux
1926 * if it was a power detach.
1929 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1930 debug("Detach returns, we are successfully detached.\n");
1931 signal(SIGHUP
, SigHup
);
1941 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1947 register char **op
, **np
;
1948 static char stybuf
[MAXSTR
];
1950 for (op
= environ
; *op
; ++op
)
1953 free((char *)NewEnv
);
1954 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1957 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1958 *np
++ = stybuf
; /* NewEnv[0] */
1959 *np
++ = Term
; /* NewEnv[1] */
1960 np
++; /* room for SHELL */
1962 np
+= 2; /* room for TERMCAP and WINDOW */
1964 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
1967 for (op
= environ
; *op
; ++op
)
1969 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
1970 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
1971 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
1972 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
1981 #if defined(USEVARARGS) && defined(__STDC__)
1982 Msg(int err
, char *fmt
, VA_DOTS
)
1984 Msg(err
, fmt
, VA_DOTS
)
1991 char buf
[MAXPATHLEN
*2];
1996 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2003 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2004 buf
[sizeof(buf
) - 1] = 0;
2006 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
2008 if (display
&& displays
)
2012 for (display
= displays
; display
; display
= display
->d_next
)
2017 /* no displays but a display - must have forked.
2018 * send message to backend!
2020 char *tty
= D_usertty
;
2021 struct display
*olddisplay
= display
;
2022 display
= 0; /* only send once */
2023 SendErrorMsg(tty
, buf
);
2024 display
= olddisplay
;
2027 printf("%s\r\n", buf
);
2031 * Call FinitTerm for all displays, write a message to each and call eexit();
2035 #if defined(USEVARARGS) && defined(__STDC__)
2036 Panic(int err
, char *fmt
, VA_DOTS
)
2038 Panic(err
, fmt
, VA_DOTS
)
2045 char buf
[MAXPATHLEN
*2];
2050 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2057 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2058 buf
[sizeof(buf
) - 1] = 0;
2060 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2061 if (displays
== 0 && display
== 0)
2063 printf("%s\r\n", buf
);
2065 Kill(PanicPid
, SIG_BYE
);
2067 else if (displays
== 0)
2069 /* no displays but a display - must have forked.
2070 * send message to backend!
2072 char *tty
= D_usertty
;
2074 SendErrorMsg(tty
, buf
);
2079 for (display
= displays
; display
; display
= display
->d_next
)
2088 SetTTY(D_userfd
, &D_OldMode
);
2089 fcntl(D_userfd
, F_SETFL
, 0);
2090 write(D_userfd
, buf
, strlen(buf
));
2091 write(D_userfd
, "\n", 1);
2094 Kill(D_userpid
, SIG_BYE
);
2097 if (tty_oldmode
>= 0)
2100 if (setuid(own_uid
))
2101 xseteuid(own_uid
); /* may be a loop. sigh. */
2105 debug1("Panic: changing back modes from %s\n", attach_tty
);
2106 chmod(attach_tty
, tty_oldmode
);
2114 * '^' is allowed as an escape mechanism for control characters. jw.
2116 * Added time insertion using ideas/code from /\ndy Jones
2117 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2122 static const char days
[] = "SunMonTueWedThuFriSat";
2123 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2126 static char winmsg_buf
[MAXSTR
];
2127 #define MAX_WINMSG_REND 16 /* rendition changes */
2128 static int winmsg_rend
[MAX_WINMSG_REND
];
2129 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2130 static int winmsg_numrend
;
2133 pad_expand(buf
, p
, numpad
, padlen
)
2142 padlen
= padlen
- (p
- buf
); /* space for rent */
2145 pn2
= pn
= p
+ padlen
;
2149 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2151 winmsg_rendpos
[--r
] = pn
- buf
;
2158 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2169 struct backtick
*next
;
2174 char result
[MAXSTR
];
2181 struct backtick
*backticks
;
2185 struct backtick
*bt
;
2190 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2194 if (c
>= ' ' || c
== '\005')
2201 backtick_fn(ev
, data
)
2205 struct backtick
*bt
;
2208 bt
= (struct backtick
*)data
;
2209 debug1("backtick_fn for #%d\n", bt
->num
);
2211 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2214 debug1("EOF on backtick #%d\n", bt
->num
);
2220 debug1("read %d bytes\n", l
);
2222 for (j
= 0; j
< l
; j
++)
2223 if (bt
->buf
[i
- j
- 1] == '\n')
2227 for (k
= i
- j
- 2; k
>= 0; k
--)
2228 if (bt
->buf
[k
] == '\n')
2231 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2232 bt
->result
[i
- j
- k
- 1] = 0;
2233 backtick_filter(bt
);
2234 WindowChanged(0, '`');
2236 if (j
== l
&& i
== MAXSTR
)
2244 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2251 setbacktick(num
, lifespan
, tick
, cmdv
)
2257 struct backtick
**btp
, *bt
;
2260 debug1("setbacktick called for backtick #%d\n", num
);
2261 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2268 for (v
= bt
->cmdv
; *v
; v
++)
2285 bt
= (struct backtick
*)malloc(sizeof *bt
);
2291 bzero(bt
, sizeof(*bt
));
2297 bt
->lifespan
= lifespan
;
2304 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2306 debug("setbacktick: continuous mode\n");
2307 bt
->buf
= (char *)malloc(MAXSTR
);
2311 setbacktick(num
, 0, 0, (char **)0);
2314 bt
->ev
.type
= EV_READ
;
2315 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2316 bt
->ev
.handler
= backtick_fn
;
2317 bt
->ev
.data
= (char *)bt
;
2324 runbacktick(bt
, tickp
, now
)
2325 struct backtick
*bt
;
2332 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2333 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2335 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2337 debug1("returning old result (%d)\n", bt
->lifespan
);
2340 f
= readpipe(bt
->cmdv
);
2344 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2346 debug1("runbacktick: read %d bytes\n", l
);
2348 for (j
= 1; j
< l
; j
++)
2349 if (bt
->result
[i
- j
- 1] == '\n')
2351 if (j
== l
&& i
== sizeof(bt
->result
))
2353 j
= sizeof(bt
->result
) / 2;
2358 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2363 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2364 if (i
&& bt
->result
[i
- 1] == '\n')
2366 debug1("runbacktick: finished, %d bytes\n", i
);
2368 backtick_filter(bt
);
2370 bt
->bestbefore
= now2
+ bt
->lifespan
;
2375 AppendWinMsgRend(str
, color
)
2380 if (winmsg_numrend
>= MAX_WINMSG_REND
)
2382 p
= winmsg_buf
+ strlen(winmsg_buf
);
2387 r
= ParseAttrColor(color
, 0, 0);
2391 winmsg_rend
[winmsg_numrend
] = r
;
2392 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2395 strncpy(p
, str
, winmsg_buf
+ sizeof(winmsg_buf
) - p
);
2399 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2409 register char *p
= winmsg_buf
;
2419 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2426 struct backtick
*bt
;
2428 if (winmsg_numrend
>= 0)
2431 winmsg_numrend
= -winmsg_numrend
;
2434 if (ScriptProcessCaption(str
, win
, padlen
))
2442 gettimeofday(&now
, NULL
);
2443 for (s
= str
; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2449 if (*s
!= '^' && *s
>= 64)
2474 if (*++s
== esc
) /* double escape ? */
2476 if ((plusflg
= *s
== '+') != 0)
2478 if ((minusflg
= *s
== '-') != 0)
2480 if ((zeroflg
= *s
== '0') != 0)
2483 while(*s
>= '0' && *s
<= '9')
2484 num
= num
* 10 + (*s
++ - '0');
2485 if ((longflg
= *s
== 'L') != 0)
2493 if ((!qmflag
&& !omflag
) || omflag
== 1)
2496 if (qmnumrend
< winmsg_numrend
)
2497 winmsg_numrend
= qmnumrend
;
2503 qmnumrend
= winmsg_numrend
;
2504 qmflag
= omflag
= 0;
2510 if (qmflag
&& omflag
!= 1)
2514 qmnumrend
= winmsg_numrend
;
2519 if (qmnumrend
< winmsg_numrend
)
2520 winmsg_numrend
= qmnumrend
;
2524 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2525 case 'a': case 'A': case 's': case 'c': case 'C':
2530 time_t nowsec
= now
.tv_sec
;
2531 tm
= localtime(&nowsec
);
2534 if (!tick
|| tick
> 3600)
2539 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2543 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2545 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2549 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2553 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2555 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2559 sprintf(p
, "%02d", tm
->tm_year
% 100);
2562 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2565 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2568 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2571 sprintf(p
, "%02d", tm
->tm_sec
);
2575 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2576 if (!tick
|| tick
> 60)
2580 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2581 if (!tick
|| tick
> 60)
2601 if (!tick
|| tick
> 60)
2610 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2617 for (bt
= backticks
; bt
; bt
= bt
->next
)
2627 char savebuf
[sizeof(winmsg_buf
)];
2629 int oldnumrend
= winmsg_numrend
;
2632 strcpy(savebuf
, winmsg_buf
);
2633 winmsg_numrend
= -winmsg_numrend
;
2634 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2635 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2636 if (!tick
|| oldtick
< tick
)
2638 if ((int)strlen(winmsg_buf
) < l
)
2639 strcat(savebuf
, winmsg_buf
);
2640 strcpy(winmsg_buf
, savebuf
);
2641 while (oldnumrend
< winmsg_numrend
)
2642 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2651 struct win
*oldfore
= 0;
2659 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2672 AddOtherUsers(p
, l
- 1, win
);
2680 AddWindowFlags(p
, l
- 1, win
);
2687 if (win
&& (int)strlen(win
->w_title
) < l
)
2689 strcpy(p
, win
->w_title
);
2699 for (i
= 0; i
< 127; i
++)
2700 if (s
[i
] && s
[i
] != '}')
2704 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2708 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2709 if (i
!= 1 || rbuf
[0] != '-')
2710 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2711 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2713 winmsg_rend
[winmsg_numrend
] = r
;
2714 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2724 if ((int)strlen(HostName
) < l
)
2726 strcpy(p
, HostName
);
2735 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2736 minusflg
= !minusflg
;
2741 truncpos
= p
- winmsg_buf
;
2742 truncper
= num
> 100 ? 100 : num
;
2743 trunclong
= longflg
;
2749 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2751 /* expand all pads */
2754 num
= (plusflg
? lastpad
: padlen
) - num
;
2755 if (!plusflg
&& padlen
== 0)
2756 num
= p
- winmsg_buf
;
2761 if (*s
!= '=' && num
== 0 && !plusflg
)
2766 num
= p
- winmsg_buf
;
2768 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2774 if (num
> MAXSTR
- 1)
2777 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2779 if (p
- winmsg_buf
> num
&& !longflg
)
2788 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2791 if (trunc
< lastpad
)
2793 left
= truncpos
- trunc
;
2794 if (left
> p
- winmsg_buf
- num
)
2795 left
= p
- winmsg_buf
- num
;
2796 debug1("lastpad = %d, ", lastpad
);
2797 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2800 if (left
+ lastpad
> p
- winmsg_buf
)
2801 left
= p
- winmsg_buf
- lastpad
;
2802 if (p
- winmsg_buf
- lastpad
- left
> 0)
2803 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2806 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2809 winmsg_rendpos
[r
] -= left
;
2810 if (winmsg_rendpos
[r
] < lastpad
)
2811 winmsg_rendpos
[r
] = lastpad
;
2815 if (p
- winmsg_buf
> lastpad
)
2816 winmsg_buf
[lastpad
] = '.';
2817 if (p
- winmsg_buf
> lastpad
+ 1)
2818 winmsg_buf
[lastpad
+ 1] = '.';
2819 if (p
- winmsg_buf
> lastpad
+ 2)
2820 winmsg_buf
[lastpad
+ 2] = '.';
2823 if (p
- winmsg_buf
> num
)
2825 p
= winmsg_buf
+ num
;
2828 if (num
- 1 >= lastpad
)
2830 if (num
- 2 >= lastpad
)
2832 if (num
- 3 >= lastpad
)
2836 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2837 winmsg_rendpos
[--r
] = num
;
2841 if (lastpad
> p
- winmsg_buf
)
2842 lastpad
= p
- winmsg_buf
;
2843 debug1("lastpad now %d\n", lastpad
);
2847 while (p
- winmsg_buf
< num
)
2849 lastpad
= p
- winmsg_buf
;
2852 debug1("lastpad2 now %d\n", lastpad
);
2858 *p
= 127; /* internal pad representation */
2872 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2874 sprintf(p
, "%*d", num
, win
->w_number
);
2881 if (qmpos
&& !qmflag
)
2886 if (padlen
> MAXSTR
- 1)
2887 padlen
= MAXSTR
- 1;
2888 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2892 evdeq(ev
); /* just in case */
2893 ev
->timeout
.tv_sec
= 0;
2894 ev
->timeout
.tv_usec
= 0;
2898 now
.tv_usec
= 100000;
2902 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2904 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2910 MakeWinMsg(s
, win
, esc
)
2915 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2919 PutWinMsg(s
, start
, max
)
2925 struct mchar rendstack
[MAX_WINMSG_REND
];
2928 if (s
!= winmsg_buf
)
2930 /* sorry, no fancy coloring available */
2931 debug1("PutWinMsg %s plain\n", s
);
2944 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
2945 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
2947 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
2949 if (p
< winmsg_rendpos
[i
])
2951 n
= winmsg_rendpos
[i
] - p
;
2968 rend
= rendstack
[--rendstackn
];
2972 rendstack
[rendstackn
++] = rend
;
2973 ApplyAttrColor(r
, &rend
);
2975 SetRendition(&rend
);
3003 if ((j
= open("/dev/null", 0)) >= 0)
3010 while (dup(++i
) < 0 && errno
!= EBADF
)
3012 debug1(" [%d]\n", i
);
3025 serv_read_fn(ev
, data
)
3029 debug("Knock - knock!\n");
3034 serv_select_fn(ev
, data
)
3040 debug("serv_select_fn called\n");
3041 /* XXX: messages?? */
3046 if (InterruptPlease
)
3048 debug("Backend received interrupt\n");
3049 /* This approach is rather questionable in a multi-display
3051 if (fore
&& displays
)
3053 #if defined(TERMIO) || defined(POSIX)
3054 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3056 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3059 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3061 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3062 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3064 write(fore
->w_ptyfd
, &ibuf
, 1);
3065 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3068 InterruptPlease
= 0;
3071 for (p
= windows
; p
; p
= p
->w_next
)
3073 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3076 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3077 p
->w_bell
= BELL_ON
;
3078 for (display
= displays
; display
; display
= display
->d_next
)
3080 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3081 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3085 p
->w_bell
= BELL_DONE
;
3086 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3088 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3090 Msg(0, "%s", VisualBellString
);
3094 debug1("using vbell timeout %d\n", VBellWait
);
3095 SetTimeout(&D_statusev
, VBellWait
);
3099 /* don't annoy the user with two messages */
3100 if (p
->w_monitor
== MON_FOUND
)
3101 p
->w_monitor
= MON_DONE
;
3102 WindowChanged(p
, 'f');
3104 if (p
->w_monitor
== MON_FOUND
)
3107 p
->w_monitor
= MON_ON
;
3108 for (display
= displays
; display
; display
= display
->d_next
)
3110 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3111 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3114 continue; /* user already sees window */
3116 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3117 continue; /* user doesn't care */
3119 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3120 p
->w_monitor
= MON_DONE
;
3122 WindowChanged(p
, 'f');
3126 for (display
= displays
; display
; display
= display
->d_next
)
3129 if (D_status
== STATUS_ON_WIN
)
3131 /* XXX: should use display functions! */
3132 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3136 /* normalize window, see resize.c */
3137 lx
= cv
->c_layer
->l_x
;
3138 ly
= cv
->c_layer
->l_y
;
3139 if (lx
== cv
->c_layer
->l_width
)
3141 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3143 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3144 cv
->c_yoff
= cv
->c_ys
- ly
;
3145 RethinkViewportOffsets(cv
);
3146 if (n
> cv
->c_layer
->l_height
)
3147 n
= cv
->c_layer
->l_height
;
3149 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3150 LayRedisplayLine(-1, -1, -1, 1);
3151 for (i
= 0; i
< n
; i
++)
3152 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3153 if (cv
== cv
->c_display
->d_forecv
)
3157 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3159 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3160 cv
->c_yoff
= cv
->c_ye
- ly
;
3161 RethinkViewportOffsets(cv
);
3162 if (n
> cv
->c_layer
->l_height
)
3163 n
= cv
->c_layer
->l_height
;
3165 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3166 LayRedisplayLine(-1, -1, -1, 1);
3167 for (i
= 0; i
< n
; i
++)
3168 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3169 if (cv
== cv
->c_display
->d_forecv
)
3173 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3175 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3176 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3177 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3178 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3179 n
= cv
->c_xs
- cv
->c_xoff
;
3181 RethinkViewportOffsets(cv
);
3182 if (n
> cv
->c_layer
->l_width
)
3183 n
= cv
->c_layer
->l_width
;
3185 LayRedisplayLine(-1, -1, -1, 1);
3186 for (i
= 0; i
< flayer
->l_height
; i
++)
3188 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3189 LayRedisplayLine(i
, 0, n
- 1, 1);
3191 if (cv
== cv
->c_display
->d_forecv
)
3195 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3197 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3198 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3199 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3200 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3201 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3203 RethinkViewportOffsets(cv
);
3204 if (n
> cv
->c_layer
->l_width
)
3205 n
= cv
->c_layer
->l_width
;
3207 LayRedisplayLine(-1, -1, -1, 1);
3208 for (i
= 0; i
< flayer
->l_height
; i
++)
3210 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3211 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3213 if (cv
== cv
->c_display
->d_forecv
)
3220 for (display
= displays
; display
; display
= display
->d_next
)
3222 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3224 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3225 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3230 logflush_fn(ev
, data
)
3238 if (!islogfile(NULL
))
3239 return; /* no more logfiles */
3241 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3244 SetTimeout(ev
, n
* 1000);
3245 evenq(ev
); /* re-enqueue ourself */
3249 /* write fancy time-stamp */
3250 for (p
= windows
; p
; p
= p
->w_next
)
3254 p
->w_logsilence
+= n
;
3255 if (p
->w_logsilence
< logtstamp_after
)
3257 if (p
->w_logsilence
- n
>= logtstamp_after
)
3259 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3260 logfwrite(p
->w_log
, buf
, strlen(buf
));
3265 * Interprets ^?, ^@ and other ^-control-char notation.
3266 * Interprets \ddd octal notation
3268 * The result is placed in *cp, p is advanced behind the parsed expression and
3277 if (*p
== '^' && p
[1])
3287 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3291 *cp
= *cp
* 8 + *p
- '0';
3292 while (*++p
<= '7' && *p
>= '0');
3303 unsigned char buf
[2];
3306 SetEscape((struct acluser
*)0, -1, -1);
3309 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3310 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3312 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);