pty.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. /*
  2. * Pseudo-tty backend for pterm.
  3. */
  4. #define _GNU_SOURCE
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <signal.h>
  10. #include <assert.h>
  11. #include <fcntl.h>
  12. #include <termios.h>
  13. #include <grp.h>
  14. #if HAVE_UTMP_H
  15. #include <utmp.h>
  16. #endif
  17. #include <pwd.h>
  18. #include <time.h>
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <sys/wait.h>
  22. #include <sys/ioctl.h>
  23. #include <errno.h>
  24. #include <termios.h>
  25. #include "putty.h"
  26. #include "ssh.h"
  27. #include "ssh/server.h" /* to check the prototypes of server-needed things */
  28. #include "tree234.h"
  29. #ifndef OMIT_UTMP
  30. #include <utmpx.h>
  31. #endif
  32. /* updwtmpx() needs the name of the wtmp file. Try to find it. */
  33. #ifndef WTMPX_FILE
  34. #ifdef _PATH_WTMPX
  35. #define WTMPX_FILE _PATH_WTMPX
  36. #else
  37. #define WTMPX_FILE "/var/log/wtmpx"
  38. #endif
  39. #endif
  40. #ifndef LASTLOG_FILE
  41. #ifdef _PATH_LASTLOG
  42. #define LASTLOG_FILE _PATH_LASTLOG
  43. #else
  44. #define LASTLOG_FILE "/var/log/lastlog"
  45. #endif
  46. #endif
  47. typedef struct Pty Pty;
  48. /*
  49. * The pty_signal_pipe, along with the SIGCHLD handler, must be
  50. * process-global rather than session-specific.
  51. */
  52. static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
  53. typedef struct PtyFd {
  54. int fd;
  55. Pty *pty;
  56. } PtyFd;
  57. struct Pty {
  58. Conf *conf;
  59. int master_fd, slave_fd;
  60. int pipefds[6];
  61. PtyFd fds[3];
  62. int master_i, master_o, master_e;
  63. Seat *seat;
  64. size_t output_backlog;
  65. char name[FILENAME_MAX];
  66. pid_t child_pid;
  67. int term_width, term_height;
  68. bool child_dead, finished;
  69. int exit_code;
  70. bufchain output_data;
  71. bool pending_eof;
  72. Backend backend;
  73. };
  74. #define PTY_MAX_BACKLOG 32768
  75. /*
  76. * We store all the (active) PtyFd structures in a tree sorted by fd,
  77. * so that when we get an uxsel notification we know which backend
  78. * instance is the owner of the pty that caused it, and then we can
  79. * find out which fd is the relevant one too.
  80. */
  81. static int ptyfd_compare(void *av, void *bv)
  82. {
  83. PtyFd *a = (PtyFd *)av;
  84. PtyFd *b = (PtyFd *)bv;
  85. if (a->fd < b->fd)
  86. return -1;
  87. else if (a->fd > b->fd)
  88. return +1;
  89. return 0;
  90. }
  91. static int ptyfd_find(void *av, void *bv)
  92. {
  93. int a = *(int *)av;
  94. PtyFd *b = (PtyFd *)bv;
  95. if (a < b->fd)
  96. return -1;
  97. else if (a > b->fd)
  98. return +1;
  99. return 0;
  100. }
  101. static tree234 *ptyfds = NULL;
  102. /*
  103. * We also have a tree of Pty structures themselves, sorted by child
  104. * pid, so that when we wait() in response to the signal we know which
  105. * backend instance is the owner of the process that caused the
  106. * signal.
  107. */
  108. static int pty_compare_by_pid(void *av, void *bv)
  109. {
  110. Pty *a = (Pty *)av;
  111. Pty *b = (Pty *)bv;
  112. if (a->child_pid < b->child_pid)
  113. return -1;
  114. else if (a->child_pid > b->child_pid)
  115. return +1;
  116. return 0;
  117. }
  118. static int pty_find_by_pid(void *av, void *bv)
  119. {
  120. pid_t a = *(pid_t *)av;
  121. Pty *b = (Pty *)bv;
  122. if (a < b->child_pid)
  123. return -1;
  124. else if (a > b->child_pid)
  125. return +1;
  126. return 0;
  127. }
  128. static tree234 *ptys_by_pid = NULL;
  129. /*
  130. * If we are using pty_pre_init(), it will need to have already
  131. * allocated a pty structure, which we must then return from
  132. * pty_init() rather than allocating a new one. Here we store that
  133. * structure between allocation and use.
  134. *
  135. * Note that although most of this module is entirely capable of
  136. * handling multiple ptys in a single process, pty_pre_init() is
  137. * fundamentally _dependent_ on there being at most one pty per
  138. * process, so the normal static-data constraints don't apply.
  139. *
  140. * Likewise, since utmp is only used via pty_pre_init, it too must
  141. * be single-instance, so we can declare utmp-related variables
  142. * here.
  143. */
  144. static Pty *single_pty = NULL;
  145. #ifndef OMIT_UTMP
  146. static pid_t pty_utmp_helper_pid = -1;
  147. static int pty_utmp_helper_pipe = -1;
  148. static bool pty_stamped_utmp;
  149. static struct utmpx utmp_entry;
  150. #endif
  151. /*
  152. * pty_argv is a grievous hack to allow a proper argv to be passed
  153. * through from the Unix command line. Again, it doesn't really
  154. * make sense outside a one-pty-per-process setup.
  155. */
  156. char **pty_argv;
  157. char *pty_osx_envrestore_prefix;
  158. static void pty_close(Pty *pty);
  159. static void pty_try_write(Pty *pty);
  160. #ifndef OMIT_UTMP
  161. static void setup_utmp(char *ttyname, char *location)
  162. {
  163. #if HAVE_LASTLOG
  164. struct lastlog lastlog_entry;
  165. FILE *lastlog;
  166. #endif
  167. struct passwd *pw;
  168. struct timeval tv;
  169. pw = getpwuid(getuid());
  170. if (!pw)
  171. return; /* can't stamp utmp if we don't have a username */
  172. memset(&utmp_entry, 0, sizeof(utmp_entry));
  173. utmp_entry.ut_type = USER_PROCESS;
  174. utmp_entry.ut_pid = getpid();
  175. #if __GNUC__ >= 8
  176. # pragma GCC diagnostic push
  177. # pragma GCC diagnostic ignored "-Wstringop-truncation"
  178. #endif // __GNUC__ >= 8
  179. strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
  180. strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
  181. strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
  182. strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
  183. #if __GNUC__ >= 8
  184. # pragma GCC diagnostic pop
  185. #endif // __GNUC__ >= 8
  186. /*
  187. * Apparently there are some architectures where (struct
  188. * utmpx).ut_tv is not essentially struct timeval (e.g. Linux
  189. * amd64). Hence the temporary.
  190. */
  191. gettimeofday(&tv, NULL);
  192. utmp_entry.ut_tv.tv_sec = tv.tv_sec;
  193. utmp_entry.ut_tv.tv_usec = tv.tv_usec;
  194. setutxent();
  195. pututxline(&utmp_entry);
  196. endutxent();
  197. #if HAVE_UPDWTMPX
  198. /* Reportedly, AIX 5.1 has <utmpx.h> and pututxline(), but no
  199. * updwtmpx(). */
  200. updwtmpx(WTMPX_FILE, &utmp_entry);
  201. #endif
  202. #if HAVE_LASTLOG
  203. memset(&lastlog_entry, 0, sizeof(lastlog_entry));
  204. strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
  205. strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
  206. time(&lastlog_entry.ll_time);
  207. if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
  208. fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
  209. fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
  210. fclose(lastlog);
  211. }
  212. #endif
  213. pty_stamped_utmp = true;
  214. }
  215. static void cleanup_utmp(void)
  216. {
  217. struct timeval tv;
  218. if (!pty_stamped_utmp)
  219. return;
  220. utmp_entry.ut_type = DEAD_PROCESS;
  221. memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
  222. gettimeofday(&tv, NULL);
  223. utmp_entry.ut_tv.tv_sec = tv.tv_sec;
  224. utmp_entry.ut_tv.tv_usec = tv.tv_usec;
  225. #if HAVE_UPDWTMPX
  226. updwtmpx(WTMPX_FILE, &utmp_entry);
  227. #endif
  228. memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
  229. utmp_entry.ut_tv.tv_sec = 0;
  230. utmp_entry.ut_tv.tv_usec = 0;
  231. setutxent();
  232. pututxline(&utmp_entry);
  233. endutxent();
  234. pty_stamped_utmp = false; /* ensure we never double-cleanup */
  235. }
  236. #endif
  237. static void sigchld_handler(int signum)
  238. {
  239. if (write(pty_signal_pipe[1], "x", 1) <= 0)
  240. /* not much we can do about it */;
  241. }
  242. static void pty_setup_sigchld_handler(void)
  243. {
  244. static bool setup = false;
  245. if (!setup) {
  246. putty_signal(SIGCHLD, sigchld_handler);
  247. setup = true;
  248. }
  249. }
  250. #ifndef OMIT_UTMP
  251. static void fatal_sig_handler(int signum)
  252. {
  253. putty_signal(signum, SIG_DFL);
  254. cleanup_utmp();
  255. raise(signum);
  256. }
  257. #endif
  258. static int pty_open_slave(Pty *pty)
  259. {
  260. if (pty->slave_fd < 0) {
  261. pty->slave_fd = open(pty->name, O_RDWR);
  262. cloexec(pty->slave_fd);
  263. }
  264. return pty->slave_fd;
  265. }
  266. static void pty_open_master(Pty *pty)
  267. {
  268. #ifdef BSD_PTYS
  269. const char chars1[] = "pqrstuvwxyz";
  270. const char chars2[] = "0123456789abcdef";
  271. const char *p1, *p2;
  272. char master_name[20];
  273. struct group *gp;
  274. for (p1 = chars1; *p1; p1++)
  275. for (p2 = chars2; *p2; p2++) {
  276. sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
  277. pty->master_fd = open(master_name, O_RDWR);
  278. if (pty->master_fd >= 0) {
  279. if (geteuid() == 0 ||
  280. access(master_name, R_OK | W_OK) == 0) {
  281. /*
  282. * We must also check at this point that we are
  283. * able to open the slave side of the pty. We
  284. * wouldn't want to allocate the wrong master,
  285. * get all the way down to forking, and _then_
  286. * find we're unable to open the slave.
  287. */
  288. strcpy(pty->name, master_name);
  289. pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
  290. cloexec(pty->master_fd);
  291. if (pty_open_slave(pty) >= 0 &&
  292. access(pty->name, R_OK | W_OK) == 0)
  293. goto got_one;
  294. if (pty->slave_fd > 0)
  295. close(pty->slave_fd);
  296. pty->slave_fd = -1;
  297. }
  298. close(pty->master_fd);
  299. }
  300. }
  301. /* If we get here, we couldn't get a tty at all. */
  302. fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
  303. exit(1);
  304. got_one:
  305. /* We need to chown/chmod the /dev/ttyXX device. */
  306. gp = getgrnam("tty");
  307. chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
  308. chmod(pty->name, 0600);
  309. #else
  310. const int flags = O_RDWR
  311. #ifdef O_NOCTTY
  312. | O_NOCTTY
  313. #endif
  314. ;
  315. #if HAVE_POSIX_OPENPT
  316. #ifdef SET_NONBLOCK_VIA_OPENPT
  317. /*
  318. * OS X, as of 10.10 at least, doesn't permit me to set O_NONBLOCK
  319. * on pty master fds via the usual fcntl mechanism. Fortunately,
  320. * it does let me work around this by adding O_NONBLOCK to the
  321. * posix_openpt flags parameter, which isn't a documented use of
  322. * the API but seems to work. So we'll do that for now.
  323. */
  324. pty->master_fd = posix_openpt(flags | O_NONBLOCK);
  325. #else
  326. pty->master_fd = posix_openpt(flags);
  327. #endif
  328. if (pty->master_fd < 0) {
  329. perror("posix_openpt");
  330. exit(1);
  331. }
  332. #else
  333. pty->master_fd = open("/dev/ptmx", flags);
  334. if (pty->master_fd < 0) {
  335. perror("/dev/ptmx: open");
  336. exit(1);
  337. }
  338. #endif
  339. if (grantpt(pty->master_fd) < 0) {
  340. perror("grantpt");
  341. exit(1);
  342. }
  343. if (unlockpt(pty->master_fd) < 0) {
  344. perror("unlockpt");
  345. exit(1);
  346. }
  347. cloexec(pty->master_fd);
  348. pty->name[FILENAME_MAX-1] = '\0';
  349. strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
  350. #endif
  351. #ifndef SET_NONBLOCK_VIA_OPENPT
  352. nonblock(pty->master_fd);
  353. #endif
  354. }
  355. static Pty *new_pty_struct(void)
  356. {
  357. Pty *pty = snew(Pty);
  358. memset(pty, 0, sizeof(Pty));
  359. pty->conf = NULL;
  360. pty->pending_eof = false;
  361. bufchain_init(&pty->output_data);
  362. return pty;
  363. }
  364. /*
  365. * Pre-initialisation. This is here to get around the fact that GTK
  366. * doesn't like being run in setuid/setgid programs (probably
  367. * sensibly). So before we initialise GTK - and therefore before we
  368. * even process the command line - we check to see if we're running
  369. * set[ug]id. If so, we open our pty master _now_, chown it as
  370. * necessary, and drop privileges. We can always close it again
  371. * later. If we're potentially going to be doing utmp as well, we
  372. * also fork off a utmp helper process and communicate with it by
  373. * means of a pipe; the utmp helper will keep privileges in order
  374. * to clean up utmp when we exit (i.e. when its end of our pipe
  375. * closes).
  376. */
  377. void pty_pre_init(void)
  378. {
  379. #ifndef NO_PTY_PRE_INIT
  380. Pty *pty;
  381. #ifndef OMIT_UTMP
  382. pid_t pid;
  383. int pipefd[2];
  384. #endif
  385. pty = single_pty = new_pty_struct();
  386. /* set the child signal handler straight away; it needs to be set
  387. * before we ever fork. */
  388. pty_setup_sigchld_handler();
  389. pty->master_fd = pty->slave_fd = -1;
  390. #ifndef OMIT_UTMP
  391. pty_stamped_utmp = false;
  392. #endif
  393. if (geteuid() != getuid() || getegid() != getgid()) {
  394. pty_open_master(pty);
  395. #ifndef OMIT_UTMP
  396. /*
  397. * Fork off the utmp helper.
  398. */
  399. if (pipe(pipefd) < 0) {
  400. perror("pterm: pipe");
  401. exit(1);
  402. }
  403. cloexec(pipefd[0]);
  404. cloexec(pipefd[1]);
  405. pid = fork();
  406. if (pid < 0) {
  407. perror("pterm: fork");
  408. exit(1);
  409. } else if (pid == 0) {
  410. char display[128], buffer[128];
  411. int dlen, ret;
  412. close(pipefd[1]);
  413. /*
  414. * Now sit here until we receive a display name from the
  415. * other end of the pipe, and then stamp utmp. Unstamp utmp
  416. * again, and exit, when the pipe closes.
  417. */
  418. dlen = 0;
  419. while (1) {
  420. ret = read(pipefd[0], buffer, lenof(buffer));
  421. if (ret <= 0) {
  422. cleanup_utmp();
  423. _exit(0);
  424. } else if (!pty_stamped_utmp) {
  425. if (dlen < lenof(display))
  426. memcpy(display+dlen, buffer,
  427. min(ret, lenof(display)-dlen));
  428. if (buffer[ret-1] == '\0') {
  429. /*
  430. * Now we have a display name. NUL-terminate
  431. * it, and stamp utmp.
  432. */
  433. display[lenof(display)-1] = '\0';
  434. /*
  435. * Trap as many fatal signals as we can in the
  436. * hope of having the best possible chance to
  437. * clean up utmp before termination. We are
  438. * unfortunately unprotected against SIGKILL,
  439. * but that's life.
  440. */
  441. putty_signal(SIGHUP, fatal_sig_handler);
  442. putty_signal(SIGINT, fatal_sig_handler);
  443. putty_signal(SIGQUIT, fatal_sig_handler);
  444. putty_signal(SIGILL, fatal_sig_handler);
  445. putty_signal(SIGABRT, fatal_sig_handler);
  446. putty_signal(SIGFPE, fatal_sig_handler);
  447. putty_signal(SIGPIPE, fatal_sig_handler);
  448. putty_signal(SIGALRM, fatal_sig_handler);
  449. putty_signal(SIGTERM, fatal_sig_handler);
  450. putty_signal(SIGSEGV, fatal_sig_handler);
  451. putty_signal(SIGUSR1, fatal_sig_handler);
  452. putty_signal(SIGUSR2, fatal_sig_handler);
  453. #ifdef SIGBUS
  454. putty_signal(SIGBUS, fatal_sig_handler);
  455. #endif
  456. #ifdef SIGPOLL
  457. putty_signal(SIGPOLL, fatal_sig_handler);
  458. #endif
  459. #ifdef SIGPROF
  460. putty_signal(SIGPROF, fatal_sig_handler);
  461. #endif
  462. #ifdef SIGSYS
  463. putty_signal(SIGSYS, fatal_sig_handler);
  464. #endif
  465. #ifdef SIGTRAP
  466. putty_signal(SIGTRAP, fatal_sig_handler);
  467. #endif
  468. #ifdef SIGVTALRM
  469. putty_signal(SIGVTALRM, fatal_sig_handler);
  470. #endif
  471. #ifdef SIGXCPU
  472. putty_signal(SIGXCPU, fatal_sig_handler);
  473. #endif
  474. #ifdef SIGXFSZ
  475. putty_signal(SIGXFSZ, fatal_sig_handler);
  476. #endif
  477. #ifdef SIGIO
  478. putty_signal(SIGIO, fatal_sig_handler);
  479. #endif
  480. setup_utmp(pty->name, display);
  481. }
  482. }
  483. }
  484. } else {
  485. close(pipefd[0]);
  486. pty_utmp_helper_pid = pid;
  487. pty_utmp_helper_pipe = pipefd[1];
  488. }
  489. #endif
  490. }
  491. /* Drop privs. */
  492. {
  493. #if HAVE_SETRESUID && HAVE_SETRESGID
  494. int gid = getgid(), uid = getuid();
  495. int setresgid(gid_t, gid_t, gid_t);
  496. int setresuid(uid_t, uid_t, uid_t);
  497. if (setresgid(gid, gid, gid) < 0) {
  498. perror("setresgid");
  499. exit(1);
  500. }
  501. if (setresuid(uid, uid, uid) < 0) {
  502. perror("setresuid");
  503. exit(1);
  504. }
  505. #else
  506. if (setgid(getgid()) < 0) {
  507. perror("setgid");
  508. exit(1);
  509. }
  510. if (setuid(getuid()) < 0) {
  511. perror("setuid");
  512. exit(1);
  513. }
  514. #endif
  515. }
  516. #endif /* NO_PTY_PRE_INIT */
  517. }
  518. static void pty_try_wait(void);
  519. static void pty_uxsel_setup(Pty *pty);
  520. static void pty_real_select_result(Pty *pty, int fd, int event, int status)
  521. {
  522. char buf[4096];
  523. int ret;
  524. bool finished = false;
  525. if (event < 0) {
  526. /*
  527. * We've been called because our child process did
  528. * something. `status' tells us what.
  529. */
  530. if ((WIFEXITED(status) || WIFSIGNALED(status))) {
  531. /*
  532. * The primary child process died.
  533. */
  534. pty->child_dead = true;
  535. del234(ptys_by_pid, pty);
  536. pty->exit_code = status;
  537. /*
  538. * If this is an ordinary pty session, this is also the
  539. * moment to terminate the whole backend.
  540. *
  541. * We _could_ instead keep the terminal open for remaining
  542. * subprocesses to output to, but conventional wisdom
  543. * seems to feel that that's the Wrong Thing for an
  544. * xterm-alike, so we bail out now (though we don't
  545. * necessarily _close_ the window, depending on the state
  546. * of Close On Exit). This would be easy enough to change
  547. * or make configurable if necessary.
  548. */
  549. if (pty->master_fd >= 0)
  550. finished = true;
  551. }
  552. } else {
  553. if (event == SELECT_R) {
  554. bool is_stdout = (fd == pty->master_o);
  555. ret = read(fd, buf, sizeof(buf));
  556. /*
  557. * Treat EIO on a pty master as equivalent to EOF (because
  558. * that's how the kernel seems to report the event where
  559. * the last process connected to the other end of the pty
  560. * went away).
  561. */
  562. if (fd == pty->master_fd && ret < 0 && errno == EIO)
  563. ret = 0;
  564. if (ret == 0) {
  565. /*
  566. * EOF on this input fd, so to begin with, we may as
  567. * well close it, and remove all references to it in
  568. * the pty's fd fields.
  569. */
  570. uxsel_del(fd);
  571. close(fd);
  572. if (pty->master_fd == fd)
  573. pty->master_fd = -1;
  574. if (pty->master_o == fd)
  575. pty->master_o = -1;
  576. if (pty->master_e == fd)
  577. pty->master_e = -1;
  578. if (is_stdout) {
  579. /*
  580. * We assume a clean exit if the pty (or stdout
  581. * pipe) has closed, but the actual child process
  582. * hasn't. The only way I can imagine this
  583. * happening is if it detaches itself from the pty
  584. * and goes daemonic - in which case the expected
  585. * usage model would precisely _not_ be for the
  586. * pterm window to hang around!
  587. */
  588. finished = true;
  589. pty_try_wait(); /* one last effort to collect exit code */
  590. if (!pty->child_dead)
  591. pty->exit_code = 0;
  592. }
  593. } else if (ret < 0) {
  594. perror("read pty master");
  595. exit(1);
  596. } else if (ret > 0) {
  597. pty->output_backlog = seat_output(
  598. pty->seat, !is_stdout, buf, ret);
  599. pty_uxsel_setup(pty);
  600. }
  601. } else if (event == SELECT_W) {
  602. /*
  603. * Attempt to send data down the pty.
  604. */
  605. pty_try_write(pty);
  606. }
  607. }
  608. if (finished && !pty->finished) {
  609. int close_on_exit;
  610. int i;
  611. for (i = 0; i < 3; i++)
  612. if (pty->fds[i].fd >= 0)
  613. uxsel_del(pty->fds[i].fd);
  614. pty_close(pty);
  615. pty->finished = true;
  616. /*
  617. * This is a slight layering-violation sort of hack: only
  618. * if we're not closing on exit (COE is set to Never, or to
  619. * Only On Clean and it wasn't a clean exit) do we output a
  620. * `terminated' message.
  621. */
  622. close_on_exit = conf_get_int(pty->conf, CONF_close_on_exit);
  623. if (close_on_exit == FORCE_OFF ||
  624. (close_on_exit == AUTO && pty->exit_code != 0)) {
  625. char *message;
  626. if (WIFEXITED(pty->exit_code)) {
  627. message = dupprintf(
  628. "\r\n[pterm: process terminated with exit code %d]\r\n",
  629. WEXITSTATUS(pty->exit_code));
  630. } else if (WIFSIGNALED(pty->exit_code)) {
  631. #if !HAVE_STRSIGNAL
  632. message = dupprintf(
  633. "\r\n[pterm: process terminated on signal %d]\r\n",
  634. WTERMSIG(pty->exit_code));
  635. #else
  636. message = dupprintf(
  637. "\r\n[pterm: process terminated on signal %d (%s)]\r\n",
  638. WTERMSIG(pty->exit_code),
  639. strsignal(WTERMSIG(pty->exit_code)));
  640. #endif
  641. } else {
  642. /* _Shouldn't_ happen, but if it does, a vague message
  643. * is better than no message at all */
  644. message = dupprintf("\r\n[pterm: process terminated]\r\n");
  645. }
  646. seat_stdout_pl(pty->seat, ptrlen_from_asciz(message));
  647. sfree(message);
  648. }
  649. seat_eof(pty->seat);
  650. seat_notify_remote_exit(pty->seat);
  651. }
  652. }
  653. static void pty_try_wait(void)
  654. {
  655. Pty *pty;
  656. pid_t pid;
  657. int status;
  658. do {
  659. pid = waitpid(-1, &status, WNOHANG);
  660. pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
  661. if (pty)
  662. pty_real_select_result(pty, -1, -1, status);
  663. } while (pid > 0);
  664. }
  665. void pty_select_result(int fd, int event)
  666. {
  667. if (fd == pty_signal_pipe[0]) {
  668. char c[1];
  669. if (read(pty_signal_pipe[0], c, 1) <= 0)
  670. /* ignore error */;
  671. /* ignore its value; it'll be `x' */
  672. pty_try_wait();
  673. } else {
  674. PtyFd *ptyfd = find234(ptyfds, &fd, ptyfd_find);
  675. if (ptyfd)
  676. pty_real_select_result(ptyfd->pty, fd, event, 0);
  677. }
  678. }
  679. static void pty_uxsel_setup_fd(Pty *pty, int fd)
  680. {
  681. int rwx = 0;
  682. if (fd < 0)
  683. return;
  684. /* read from standard output and standard error pipes, assuming
  685. * we're not too backlogged */
  686. if ((pty->master_o == fd || pty->master_e == fd) &&
  687. pty->output_backlog < PTY_MAX_BACKLOG)
  688. rwx |= SELECT_R;
  689. /* write to standard input pipe if we have any data */
  690. if (pty->master_i == fd && bufchain_size(&pty->output_data))
  691. rwx |= SELECT_W;
  692. uxsel_set(fd, rwx, pty_select_result);
  693. }
  694. static void pty_uxsel_setup(Pty *pty)
  695. {
  696. /*
  697. * We potentially have three separate fds here, but on the other
  698. * hand, some of them might be the same (if they're a pty master).
  699. * So we can't just call uxsel_set(master_o, SELECT_R) and then
  700. * uxsel_set(master_i, SELECT_W), without the latter potentially
  701. * undoing the work of the former if master_o == master_i.
  702. *
  703. * Instead, here we call a single uxsel on each one of these fds
  704. * (if it exists at all), and for each one, check it against all
  705. * three to see which bits to set.
  706. */
  707. pty_uxsel_setup_fd(pty, pty->master_o);
  708. pty_uxsel_setup_fd(pty, pty->master_e);
  709. pty_uxsel_setup_fd(pty, pty->master_i);
  710. /*
  711. * In principle this only needs calling once for all pty
  712. * backend instances, but it's simplest just to call it every
  713. * time; uxsel won't mind.
  714. */
  715. uxsel_set(pty_signal_pipe[0], SELECT_R, pty_select_result);
  716. }
  717. static void copy_ttymodes_into_termios(
  718. struct termios *attrs, struct ssh_ttymodes modes)
  719. {
  720. #define TTYMODE_CHAR(name, ssh_opcode, cc_index) { \
  721. if (modes.have_mode[ssh_opcode]) { \
  722. unsigned value = modes.mode_val[ssh_opcode]; \
  723. /* normalise wire value of 255 to local _POSIX_VDISABLE */ \
  724. attrs->c_cc[cc_index] = (value == 255 ? \
  725. _POSIX_VDISABLE : value); \
  726. } \
  727. }
  728. #define TTYMODE_FLAG(flagval, ssh_opcode, field, flagmask) { \
  729. if (modes.have_mode[ssh_opcode]) { \
  730. attrs->c_##field##flag &= ~flagmask; \
  731. if (modes.mode_val[ssh_opcode]) \
  732. attrs->c_##field##flag |= flagval; \
  733. } \
  734. }
  735. #define TTYMODES_LOCAL_ONLY /* omit any that this platform doesn't know */
  736. #include "ssh/ttymode-list.h"
  737. #undef TTYMODES_LOCAL_ONLY
  738. #undef TTYMODE_CHAR
  739. #undef TTYMODE_FLAG
  740. if (modes.have_mode[TTYMODE_ISPEED])
  741. cfsetispeed(attrs, modes.mode_val[TTYMODE_ISPEED]);
  742. if (modes.have_mode[TTYMODE_OSPEED])
  743. cfsetospeed(attrs, modes.mode_val[TTYMODE_OSPEED]);
  744. }
  745. /*
  746. * The main setup function for the pty back end. This doesn't match
  747. * the signature of backend_init(), partly because it has to be able
  748. * to take extra arguments such as an argv array, and also because
  749. * once we're changing the type signature _anyway_ we can discard the
  750. * stuff that's not really applicable to this backend like host names
  751. * and port numbers.
  752. */
  753. Backend *pty_backend_create(
  754. Seat *seat, LogContext *logctx, Conf *conf, char **argv, const char *cmd,
  755. struct ssh_ttymodes ttymodes, bool pipes_instead, const char *dir,
  756. const char *const *env_vars_to_unset)
  757. {
  758. int slavefd;
  759. pid_t pid, pgrp;
  760. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  761. bool got_windowid;
  762. long windowid;
  763. #endif
  764. Pty *pty;
  765. int i;
  766. /* No local authentication phase in this protocol */
  767. seat_set_trust_status(seat, false);
  768. if (single_pty) {
  769. pty = single_pty;
  770. assert(pty->conf == NULL);
  771. } else {
  772. pty = new_pty_struct();
  773. pty->master_fd = pty->slave_fd = -1;
  774. #ifndef OMIT_UTMP
  775. pty_stamped_utmp = false;
  776. #endif
  777. }
  778. for (i = 0; i < 6; i++)
  779. pty->pipefds[i] = -1;
  780. for (i = 0; i < 3; i++) {
  781. pty->fds[i].fd = -1;
  782. pty->fds[i].pty = pty;
  783. }
  784. if (pty_signal_pipe[0] < 0) {
  785. if (pipe(pty_signal_pipe) < 0) {
  786. perror("pipe");
  787. exit(1);
  788. }
  789. cloexec(pty_signal_pipe[0]);
  790. cloexec(pty_signal_pipe[1]);
  791. }
  792. pty->seat = seat;
  793. pty->backend.vt = &pty_backend;
  794. pty->conf = conf_copy(conf);
  795. pty->term_width = conf_get_int(conf, CONF_width);
  796. pty->term_height = conf_get_int(conf, CONF_height);
  797. if (!ptyfds)
  798. ptyfds = newtree234(ptyfd_compare);
  799. if (pipes_instead) {
  800. if (pty->master_fd >= 0) {
  801. /* If somehow we've got a pty master already and don't
  802. * need it, throw it away! */
  803. close(pty->master_fd);
  804. #ifndef OMIT_UTMP
  805. if (pty_utmp_helper_pipe >= 0) {
  806. close(pty_utmp_helper_pipe); /* don't need this either */
  807. pty_utmp_helper_pipe = -1;
  808. }
  809. #endif
  810. }
  811. for (i = 0; i < 6; i += 2) {
  812. if (pipe(pty->pipefds + i) < 0) {
  813. backend_free(&pty->backend);
  814. return NULL;
  815. }
  816. }
  817. pty->fds[0].fd = pty->master_i = pty->pipefds[1];
  818. pty->fds[1].fd = pty->master_o = pty->pipefds[2];
  819. pty->fds[2].fd = pty->master_e = pty->pipefds[4];
  820. add234(ptyfds, &pty->fds[0]);
  821. add234(ptyfds, &pty->fds[1]);
  822. add234(ptyfds, &pty->fds[2]);
  823. } else {
  824. if (pty->master_fd < 0)
  825. pty_open_master(pty);
  826. #ifndef OMIT_UTMP
  827. /*
  828. * Stamp utmp (that is, tell the utmp helper process to do so),
  829. * or not.
  830. */
  831. if (pty_utmp_helper_pipe >= 0) { /* if it's < 0, we can't anyway */
  832. if (!conf_get_bool(conf, CONF_stamp_utmp)) {
  833. /* We're not stamping utmp, so just let the child
  834. * process die that was waiting to unstamp it later. */
  835. close(pty_utmp_helper_pipe);
  836. pty_utmp_helper_pipe = -1;
  837. } else {
  838. const char *location = seat_get_x_display(pty->seat);
  839. int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
  840. while (pos < len) {
  841. int ret = write(pty_utmp_helper_pipe,
  842. location + pos, len - pos);
  843. if (ret < 0) {
  844. perror("pterm: writing to utmp helper process");
  845. close(pty_utmp_helper_pipe); /* arrgh, just give up */
  846. pty_utmp_helper_pipe = -1;
  847. break;
  848. }
  849. pos += ret;
  850. }
  851. }
  852. }
  853. #endif
  854. pty->master_i = pty->master_fd;
  855. pty->master_o = pty->master_fd;
  856. pty->master_e = -1;
  857. pty->fds[0].fd = pty->master_fd;
  858. add234(ptyfds, &pty->fds[0]);
  859. }
  860. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  861. got_windowid = seat_get_windowid(pty->seat, &windowid);
  862. #endif
  863. /*
  864. * Set up the signal handler to catch SIGCHLD, if pty_pre_init
  865. * didn't already do it.
  866. */
  867. pty_setup_sigchld_handler();
  868. /*
  869. * Fork and execute the command.
  870. */
  871. pid = fork();
  872. if (pid < 0) {
  873. perror("fork");
  874. exit(1);
  875. }
  876. if (pid == 0) {
  877. struct termios attrs;
  878. /*
  879. * We are the child.
  880. */
  881. if (pty_osx_envrestore_prefix) {
  882. int plen = strlen(pty_osx_envrestore_prefix);
  883. extern char **environ;
  884. char **ep;
  885. restart_osx_env_restore:
  886. for (ep = environ; *ep; ep++) {
  887. char *e = *ep;
  888. if (!strncmp(e, pty_osx_envrestore_prefix, plen)) {
  889. bool unset = (e[plen] == 'u');
  890. char *pname = dupprintf("%.*s", (int)strcspn(e, "="), e);
  891. char *name = pname + plen + 1;
  892. char *value = e + strcspn(e, "=");
  893. if (*value) value++;
  894. value = dupstr(value);
  895. if (unset)
  896. unsetenv(name);
  897. else
  898. setenv(name, value, 1);
  899. unsetenv(pname);
  900. sfree(pname);
  901. sfree(value);
  902. goto restart_osx_env_restore;
  903. }
  904. }
  905. }
  906. pgrp = getpid();
  907. if (pipes_instead) {
  908. int i;
  909. dup2(pty->pipefds[0], 0);
  910. dup2(pty->pipefds[3], 1);
  911. dup2(pty->pipefds[5], 2);
  912. for (i = 0; i < 6; i++)
  913. close(pty->pipefds[i]);
  914. setsid();
  915. } else {
  916. slavefd = pty_open_slave(pty);
  917. if (slavefd < 0) {
  918. perror("slave pty: open");
  919. _exit(1);
  920. }
  921. close(pty->master_fd);
  922. noncloexec(slavefd);
  923. dup2(slavefd, 0);
  924. dup2(slavefd, 1);
  925. dup2(slavefd, 2);
  926. close(slavefd);
  927. setsid();
  928. #ifdef TIOCSCTTY
  929. ioctl(0, TIOCSCTTY, 1);
  930. #endif
  931. tcsetpgrp(0, pgrp);
  932. /*
  933. * Set up configuration-dependent termios settings on the new
  934. * pty. Linux would have let us do this on the pty master
  935. * before we forked, but that fails on OS X, so we do it here
  936. * instead.
  937. */
  938. if (tcgetattr(0, &attrs) == 0) {
  939. /*
  940. * Set the backspace character to be whichever of ^H and
  941. * ^? is specified by bksp_is_delete.
  942. */
  943. attrs.c_cc[VERASE] = conf_get_bool(conf, CONF_bksp_is_delete)
  944. ? '\177' : '\010';
  945. /*
  946. * Set the IUTF8 bit iff the character set is UTF-8.
  947. */
  948. #ifdef IUTF8
  949. if (seat_is_utf8(seat))
  950. attrs.c_iflag |= IUTF8;
  951. else
  952. attrs.c_iflag &= ~IUTF8;
  953. #endif
  954. copy_ttymodes_into_termios(&attrs, ttymodes);
  955. tcsetattr(0, TCSANOW, &attrs);
  956. }
  957. }
  958. setpgid(pgrp, pgrp);
  959. if (!pipes_instead) {
  960. int ptyfd = open(pty->name, O_WRONLY, 0);
  961. if (ptyfd >= 0)
  962. close(ptyfd);
  963. }
  964. setpgid(pgrp, pgrp);
  965. if (env_vars_to_unset)
  966. for (const char *const *p = env_vars_to_unset; *p; p++)
  967. unsetenv(*p);
  968. if (!pipes_instead) {
  969. char *term_env_var = dupprintf("TERM=%s",
  970. conf_get_str(conf, CONF_termtype));
  971. putenv(term_env_var);
  972. /* We mustn't free term_env_var, as putenv links it into the
  973. * environment in place.
  974. */
  975. }
  976. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  977. if (got_windowid) {
  978. char *windowid_env_var = dupprintf("WINDOWID=%ld", windowid);
  979. putenv(windowid_env_var);
  980. /* We mustn't free windowid_env_var, as putenv links it into the
  981. * environment in place.
  982. */
  983. }
  984. {
  985. /*
  986. * In case we were invoked with a --display argument that
  987. * doesn't match DISPLAY in our actual environment, we
  988. * should set DISPLAY for processes running inside the
  989. * terminal to match the display the terminal itself is
  990. * on.
  991. */
  992. const char *x_display = seat_get_x_display(pty->seat);
  993. if (x_display) {
  994. char *x_display_env_var = dupprintf("DISPLAY=%s", x_display);
  995. putenv(x_display_env_var);
  996. /* As above, we don't free this. */
  997. } else {
  998. unsetenv("DISPLAY");
  999. }
  1000. }
  1001. #endif
  1002. {
  1003. char *key, *val;
  1004. for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key);
  1005. val != NULL;
  1006. val = conf_get_str_strs(conf, CONF_environmt, key, &key)) {
  1007. char *varval = dupcat(key, "=", val);
  1008. putenv(varval);
  1009. /*
  1010. * We must not free varval, since putenv links it
  1011. * into the environment _in place_. Weird, but
  1012. * there we go. Memory usage will be rationalised
  1013. * as soon as we exec anyway.
  1014. */
  1015. }
  1016. }
  1017. if (dir) {
  1018. if (chdir(dir) < 0) {
  1019. /* Ignore the error - nothing we can sensibly do about it,
  1020. * and our existing cwd is as good a fallback as any. */
  1021. }
  1022. }
  1023. /*
  1024. * SIGINT, SIGQUIT and SIGPIPE may have been set to ignored by
  1025. * our parent, particularly by things like sh -c 'pterm &' and
  1026. * some window or session managers. SIGPIPE was also
  1027. * (potentially) blocked by us during startup. Reverse all
  1028. * this for our child process.
  1029. */
  1030. putty_signal(SIGINT, SIG_DFL);
  1031. putty_signal(SIGQUIT, SIG_DFL);
  1032. putty_signal(SIGPIPE, SIG_DFL);
  1033. block_signal(SIGPIPE, false);
  1034. if (argv || cmd) {
  1035. /*
  1036. * If we were given a separated argument list, try to exec
  1037. * it.
  1038. */
  1039. if (argv) {
  1040. execvp(argv[0], argv);
  1041. }
  1042. /*
  1043. * Otherwise, if we were given a single command string,
  1044. * try passing that to $SHELL -c.
  1045. *
  1046. * In the case of pterm, this system of fallbacks arranges
  1047. * that we can _either_ follow 'pterm -e' with a list of
  1048. * argv elements to be fed directly to exec, _or_ with a
  1049. * single argument containing a command to be parsed by a
  1050. * shell (but, in cases of doubt, the former is more
  1051. * reliable). We arrange this by setting argv to the full
  1052. * argument list, and also setting cmd to the single
  1053. * element of argv if it's a length-1 list.
  1054. *
  1055. * A quick survey of other terminal emulators' -e options
  1056. * (as of Debian squeeze) suggests that:
  1057. *
  1058. * - xterm supports both modes, more or less like this
  1059. * - gnome-terminal will only accept a one-string shell command
  1060. * - Eterm, kterm and rxvt will only accept a list of
  1061. * argv elements (as did older versions of pterm).
  1062. *
  1063. * It therefore seems important to support both usage
  1064. * modes in order to be a drop-in replacement for either
  1065. * xterm or gnome-terminal, and hence for anyone's
  1066. * plausible uses of the Debian-style alias
  1067. * 'x-terminal-emulator'.
  1068. *
  1069. * In other use cases, a caller can set only one of argv
  1070. * and cmd to get a fixed handling of the input.
  1071. */
  1072. if (cmd) {
  1073. char *shell = getenv("SHELL");
  1074. if (shell)
  1075. execl(shell, shell, "-c", cmd, (void *)NULL);
  1076. }
  1077. } else {
  1078. const char *shell = getenv("SHELL");
  1079. if (!shell)
  1080. shell = "/bin/sh";
  1081. char *shellname;
  1082. if (conf_get_bool(conf, CONF_login_shell)) {
  1083. const char *p = strrchr(shell, '/');
  1084. p = p ? p+1 : shell;
  1085. shellname = dupprintf("-%s", p);
  1086. } else
  1087. shellname = (char *)shell;
  1088. execl(shell, shellname, (void *)NULL);
  1089. }
  1090. /*
  1091. * If we're here, exec has gone badly foom.
  1092. */
  1093. perror("exec");
  1094. _exit(127);
  1095. } else {
  1096. pty->child_pid = pid;
  1097. pty->child_dead = false;
  1098. pty->finished = false;
  1099. if (pty->slave_fd > 0)
  1100. close(pty->slave_fd);
  1101. if (!ptys_by_pid)
  1102. ptys_by_pid = newtree234(pty_compare_by_pid);
  1103. if (pty->pipefds[0] >= 0) {
  1104. close(pty->pipefds[0]);
  1105. pty->pipefds[0] = -1;
  1106. }
  1107. if (pty->pipefds[3] >= 0) {
  1108. close(pty->pipefds[3]);
  1109. pty->pipefds[3] = -1;
  1110. }
  1111. if (pty->pipefds[5] >= 0) {
  1112. close(pty->pipefds[5]);
  1113. pty->pipefds[5] = -1;
  1114. }
  1115. add234(ptys_by_pid, pty);
  1116. }
  1117. pty_uxsel_setup(pty);
  1118. return &pty->backend;
  1119. }
  1120. /*
  1121. * This is the pty backend's _official_ init method, for BackendVtable
  1122. * purposes. Its job is just to be an API converter, ignoring the
  1123. * irrelevant input parameters and making up auxiliary outputs. Also
  1124. * it gets the argv array from the global variable pty_argv, expecting
  1125. * that it will have been invoked by pterm.
  1126. */
  1127. static char *pty_init(const BackendVtable *vt, Seat *seat,
  1128. Backend **backend_handle, LogContext *logctx,
  1129. Conf *conf, const char *host, int port,
  1130. char **realhost, bool nodelay, bool keepalive)
  1131. {
  1132. const char *cmd = NULL;
  1133. struct ssh_ttymodes modes;
  1134. memset(&modes, 0, sizeof(modes));
  1135. if (pty_argv && pty_argv[0] && !pty_argv[1])
  1136. cmd = pty_argv[0];
  1137. assert(vt == &pty_backend);
  1138. *backend_handle = pty_backend_create(
  1139. seat, logctx, conf, pty_argv, cmd, modes, false, NULL, NULL);
  1140. *realhost = dupstr("");
  1141. return NULL;
  1142. }
  1143. static void pty_reconfig(Backend *be, Conf *conf)
  1144. {
  1145. Pty *pty = container_of(be, Pty, backend);
  1146. /*
  1147. * We don't have much need to reconfigure this backend, but
  1148. * unfortunately we do need to pick up the setting of Close On
  1149. * Exit so we know whether to give a `terminated' message.
  1150. */
  1151. conf_copy_into(pty->conf, conf);
  1152. }
  1153. /*
  1154. * Stub routine (never called in pterm).
  1155. */
  1156. static void pty_free(Backend *be)
  1157. {
  1158. Pty *pty = container_of(be, Pty, backend);
  1159. int i;
  1160. pty_close(pty);
  1161. /* Either of these may fail `not found'. That's fine with us. */
  1162. del234(ptys_by_pid, pty);
  1163. for (i = 0; i < 3; i++)
  1164. if (pty->fds[i].fd >= 0)
  1165. del234(ptyfds, &pty->fds[i]);
  1166. bufchain_clear(&pty->output_data);
  1167. conf_free(pty->conf);
  1168. pty->conf = NULL;
  1169. if (pty == single_pty) {
  1170. /*
  1171. * Leave this structure around in case we need to Restart
  1172. * Session.
  1173. */
  1174. } else {
  1175. sfree(pty);
  1176. }
  1177. }
  1178. static void pty_try_write(Pty *pty)
  1179. {
  1180. ssize_t ret;
  1181. assert(pty->master_i >= 0);
  1182. while (bufchain_size(&pty->output_data) > 0) {
  1183. ptrlen data = bufchain_prefix(&pty->output_data);
  1184. ret = write(pty->master_i, data.ptr, data.len);
  1185. if (ret < 0 && (errno == EWOULDBLOCK)) {
  1186. /*
  1187. * We've sent all we can for the moment.
  1188. */
  1189. break;
  1190. }
  1191. if (ret < 0) {
  1192. perror("write pty master");
  1193. exit(1);
  1194. }
  1195. bufchain_consume(&pty->output_data, ret);
  1196. }
  1197. if (pty->pending_eof && bufchain_size(&pty->output_data) == 0) {
  1198. /* This should only happen if pty->master_i is a pipe that
  1199. * doesn't alias either output fd */
  1200. assert(pty->master_i != pty->master_o);
  1201. assert(pty->master_i != pty->master_e);
  1202. uxsel_del(pty->master_i);
  1203. close(pty->master_i);
  1204. pty->master_i = -1;
  1205. pty->pending_eof = false;
  1206. }
  1207. pty_uxsel_setup(pty);
  1208. }
  1209. /*
  1210. * Called to send data down the pty.
  1211. */
  1212. static void pty_send(Backend *be, const char *buf, size_t len)
  1213. {
  1214. Pty *pty = container_of(be, Pty, backend);
  1215. if (pty->master_i < 0 || pty->pending_eof)
  1216. return; /* ignore all writes if fd closed */
  1217. bufchain_add(&pty->output_data, buf, len);
  1218. pty_try_write(pty);
  1219. }
  1220. static void pty_close(Pty *pty)
  1221. {
  1222. int i;
  1223. if (pty->master_o >= 0)
  1224. uxsel_del(pty->master_o);
  1225. if (pty->master_e >= 0)
  1226. uxsel_del(pty->master_e);
  1227. if (pty->master_i >= 0)
  1228. uxsel_del(pty->master_i);
  1229. if (pty->master_fd >= 0) {
  1230. close(pty->master_fd);
  1231. pty->master_fd = -1;
  1232. }
  1233. for (i = 0; i < 6; i++) {
  1234. if (pty->pipefds[i] >= 0)
  1235. close(pty->pipefds[i]);
  1236. pty->pipefds[i] = -1;
  1237. }
  1238. pty->master_i = pty->master_o = pty->master_e = -1;
  1239. #ifndef OMIT_UTMP
  1240. if (pty_utmp_helper_pipe >= 0) {
  1241. close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
  1242. pty_utmp_helper_pipe = -1;
  1243. }
  1244. #endif
  1245. }
  1246. /*
  1247. * Called to query the current socket sendability status.
  1248. */
  1249. static size_t pty_sendbuffer(Backend *be)
  1250. {
  1251. Pty *pty = container_of(be, Pty, backend);
  1252. return bufchain_size(&pty->output_data);
  1253. }
  1254. /*
  1255. * Called to set the size of the window
  1256. */
  1257. static void pty_size(Backend *be, int width, int height)
  1258. {
  1259. Pty *pty = container_of(be, Pty, backend);
  1260. struct winsize size;
  1261. int xpixel = 0, ypixel = 0;
  1262. pty->term_width = width;
  1263. pty->term_height = height;
  1264. if (pty->master_fd < 0)
  1265. return;
  1266. seat_get_window_pixel_size(pty->seat, &xpixel, &ypixel);
  1267. size.ws_row = (unsigned short)pty->term_height;
  1268. size.ws_col = (unsigned short)pty->term_width;
  1269. size.ws_xpixel = (unsigned short)xpixel;
  1270. size.ws_ypixel = (unsigned short)ypixel;
  1271. ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
  1272. return;
  1273. }
  1274. /*
  1275. * Send special codes.
  1276. */
  1277. static void pty_special(Backend *be, SessionSpecialCode code, int arg)
  1278. {
  1279. Pty *pty = container_of(be, Pty, backend);
  1280. if (code == SS_BRK) {
  1281. if (pty->master_fd >= 0)
  1282. tcsendbreak(pty->master_fd, 0);
  1283. return;
  1284. }
  1285. if (code == SS_EOF) {
  1286. if (pty->master_i >= 0 && pty->master_i != pty->master_fd) {
  1287. pty->pending_eof = true;
  1288. pty_try_write(pty);
  1289. }
  1290. return;
  1291. }
  1292. {
  1293. int sig = -1;
  1294. #define SIGNAL_SUB(name) if (code == SS_SIG ## name) sig = SIG ## name;
  1295. #define SIGNAL_MAIN(name, text) SIGNAL_SUB(name)
  1296. #define SIGNALS_LOCAL_ONLY
  1297. #include "ssh/signal-list.h"
  1298. #undef SIGNAL_SUB
  1299. #undef SIGNAL_MAIN
  1300. #undef SIGNALS_LOCAL_ONLY
  1301. if (sig != -1) {
  1302. if (!pty->child_dead)
  1303. kill(pty->child_pid, sig);
  1304. return;
  1305. }
  1306. }
  1307. return;
  1308. }
  1309. /*
  1310. * Return a list of the special codes that make sense in this
  1311. * protocol.
  1312. */
  1313. static const SessionSpecial *pty_get_specials(Backend *be)
  1314. {
  1315. /* Pty *pty = container_of(be, Pty, backend); */
  1316. /*
  1317. * Hmm. When I get round to having this actually usable, it
  1318. * might be quite nice to have the ability to deliver a few
  1319. * well chosen signals to the child process - SIGINT, SIGTERM,
  1320. * SIGKILL at least.
  1321. */
  1322. return NULL;
  1323. }
  1324. static bool pty_connected(Backend *be)
  1325. {
  1326. /* Pty *pty = container_of(be, Pty, backend); */
  1327. return true;
  1328. }
  1329. static bool pty_sendok(Backend *be)
  1330. {
  1331. /* Pty *pty = container_of(be, Pty, backend); */
  1332. return true;
  1333. }
  1334. static void pty_unthrottle(Backend *be, size_t backlog)
  1335. {
  1336. Pty *pty = container_of(be, Pty, backend);
  1337. pty->output_backlog = backlog;
  1338. pty_uxsel_setup(pty);
  1339. }
  1340. static bool pty_ldisc(Backend *be, int option)
  1341. {
  1342. /* Pty *pty = container_of(be, Pty, backend); */
  1343. return false; /* neither editing nor echoing */
  1344. }
  1345. static void pty_provide_ldisc(Backend *be, Ldisc *ldisc)
  1346. {
  1347. /* Pty *pty = container_of(be, Pty, backend); */
  1348. /* This is a stub. */
  1349. }
  1350. static int pty_exitcode(Backend *be)
  1351. {
  1352. Pty *pty = container_of(be, Pty, backend);
  1353. if (!pty->finished)
  1354. return -1; /* not dead yet */
  1355. else if (WIFSIGNALED(pty->exit_code))
  1356. return 128 + WTERMSIG(pty->exit_code);
  1357. else
  1358. return WEXITSTATUS(pty->exit_code);
  1359. }
  1360. int pty_backend_exit_signum(Backend *be)
  1361. {
  1362. Pty *pty = container_of(be, Pty, backend);
  1363. if (!pty->finished || !WIFSIGNALED(pty->exit_code))
  1364. return -1;
  1365. return WTERMSIG(pty->exit_code);
  1366. }
  1367. ptrlen pty_backend_exit_signame(Backend *be, char **aux_msg)
  1368. {
  1369. *aux_msg = NULL;
  1370. int sig = pty_backend_exit_signum(be);
  1371. if (sig < 0)
  1372. return PTRLEN_LITERAL("");
  1373. #define SIGNAL_SUB(s) { \
  1374. if (sig == SIG ## s) \
  1375. return PTRLEN_LITERAL(#s); \
  1376. }
  1377. #define SIGNAL_MAIN(s, desc) SIGNAL_SUB(s)
  1378. #define SIGNALS_LOCAL_ONLY
  1379. #include "ssh/signal-list.h"
  1380. #undef SIGNAL_MAIN
  1381. #undef SIGNAL_SUB
  1382. #undef SIGNALS_LOCAL_ONLY
  1383. *aux_msg = dupprintf("untranslatable signal number %d: %s",
  1384. sig, strsignal(sig));
  1385. return PTRLEN_LITERAL("HUP"); /* need some kind of default */
  1386. }
  1387. static int pty_cfg_info(Backend *be)
  1388. {
  1389. /* Pty *pty = container_of(be, Pty, backend); */
  1390. return 0;
  1391. }
  1392. const BackendVtable pty_backend = {
  1393. .init = pty_init,
  1394. .free = pty_free,
  1395. .reconfig = pty_reconfig,
  1396. .send = pty_send,
  1397. .sendbuffer = pty_sendbuffer,
  1398. .size = pty_size,
  1399. .special = pty_special,
  1400. .get_specials = pty_get_specials,
  1401. .connected = pty_connected,
  1402. .exitcode = pty_exitcode,
  1403. .sendok = pty_sendok,
  1404. .ldisc_option_state = pty_ldisc,
  1405. .provide_ldisc = pty_provide_ldisc,
  1406. .unthrottle = pty_unthrottle,
  1407. .cfg_info = pty_cfg_info,
  1408. .id = "pty",
  1409. .displayname_tc = "pty",
  1410. .displayname_lc = "pty",
  1411. .protocol = -1,
  1412. };