@@ -40,6 +40,10 @@ function command($path,$file) {
4040 global $ run ,$ wait ,$ rows ;
4141 return (file_exists ($ file ) && substr ($ file ,0 ,strlen ($ path ))==$ path ) ? "$ run tail -f -n $ rows ' $ file' " : $ wait ;
4242}
43+ function sed_escape ($ s ) {
44+ // escape sed replacement meta characters: & and \
45+ return str_replace (['\\' , '& ' ], ['\\\\' , '\\& ' ], $ s );
46+ }
4347switch ($ _GET ['tag ' ]) {
4448case 'ttyd ' :
4549 // check if ttyd already running
@@ -65,29 +69,36 @@ function command($path,$file) {
6569 $ real_path = '/root ' ;
6670 }
6771
68- $ name = unbundle ($ _GET ['name ' ]);
69- $ exec = "/var/tmp/ $ name.run.sh " ;
72+ // Set script variables
73+ $ unique_id = getmypid () . '_ ' . uniqid (); // prevent race condition with multiple terminals
74+ $ exec = "/var/tmp/file.manager.terminal. $ unique_id.sh " ;
75+ $ profile = "/tmp/file.manager.terminal. $ unique_id.profile " ;
7076 $ escaped_path = str_replace ("' " , "' \\'' " , $ real_path );
71- // Escape sed metacharacters: & (matched string), \\ (escape char), / (delimiter)
72- $ sed_escaped = str_replace (['\\' , '& ' , '/ ' ], ['\\\\' , '\\& ' , '\\/ ' ], $ escaped_path );
77+ $ sed_escaped = sed_escape ($ escaped_path );
78+
79+ // Get user's shell (same as standard terminal)
80+ $ user_shell = posix_getpwuid (0 )['shell ' ];
7381
7482 // Create startup script similar to ~/.bashrc
7583 // Note: We can not use ~/.bashrc as it loads /etc/profile which does 'cd $HOME'
84+ // Note: Script deletes itself before exec (bash has already loaded the script into memory)
7685 $ script_content = <<<BASH
7786#!/bin/bash
7887# Modify /etc/profile to replace 'cd \$HOME' with our target path
79- sed 's#^cd \$HOME#cd '\'' $ sed_escaped'\''#' /etc/profile > /tmp/ $ name . profile
80- source /tmp/ $ name . profile
88+ sed 's#^cd \$HOME#cd '\'' $ sed_escaped'\''#' /etc/profile > ' $ profile'
89+ source ' $ profile'
8190source /root/.bash_profile 2>/dev/null
82- rm /tmp/ $ name.profile
83- exec bash --norc -i
91+ rm ' $ profile'
92+ # Delete this script and exec shell (bash has already loaded this into memory)
93+ { rm -f ' $ exec'; exec $ user_shell --norc -i; }
8494BASH ;
8595
8696 file_put_contents ($ exec , $ script_content );
8797 chmod ($ exec , 0755 );
8898 exec ("ttyd-exec -i ' $ sock' $ exec " );
99+
100+ // Standard login shell
89101 } else {
90- // Standard login shell
91102 if ($ retval != 0 ) exec ("ttyd-exec -i ' $ sock' ' " . posix_getpwuid (0 )['shell ' ] . "' --login " );
92103 }
93104 break ;
0 commit comments